我最近将MySQL升级到5.1.41。在升级之前,以下SQL起作用了(或者至少我以为我记得它起作用了……自设计此工具以来已经有几个星期了……)。现在,SQL给了我一个错误,指出“已存档”列不明确。我该怎么写呢?还是我不知道有其他问题?

我只想返回“ unit_id”,“ lease_count”(存储在另一个表中的unit_id应该与“ a.unit_id”相对应)和“ lease_archived_count”(存储在另一个表中的unit_id应该与“ a.unit_id”)。

SELECT a.unit_id,
    (SELECT count(*) FROM o_leases WHERE unit_id = a.unit_id AND archived = 0) as lease_count,
    (SELECT count(*) FROM o_leases WHERE unit_id = a.unit_id AND archived = 1) as lease_archive_count

FROM p_unit a, properties b, portfolio c

WHERE a.property_id = b.properties_id
AND b.portfolio_id = c.portfolio_id
AND a.archived = 0


谢谢你的帮助。

最佳答案

该错误仅指一个地方。我建议给sub select中的表也提供一个别名:

(SELECT count(*) FROM o_leases o WHERE o.unit_id = a.unit_id AND o.archived = 0) as lease_count,
(SELECT count(*) FROM o_leases o WHERE o.unit_id = a.unit_id AND o.archived = 1) as lease_archive_count


似乎与archivedp_unit字段冲突。

08-06 17:48