列别名在WHERE子句中不可用

时间:2015-07-10 18:05:22

标签: mysql

我编写了一个基于关键字/选择菜单搜索系统构建查询的php脚本。该脚本运行良好,直到我尝试搜索列别名:

SELECT
    contacts.*,
    orders.order_id AS is_customer,
    purchases.purchase_id AS is_supplier
FROM contacts
LEFT JOIN orders ON orders.customer_id=contacts.contact_id
LEFT JOIN purchases ON purchases.supplier_id=contacts.contact_id
WHERE is_customer IS NOT NULL
AND contacts.account_id=1
GROUP BY contact_id
ORDER BY contact_company_name

WHERE is_customer IS NOT NULL就是问题--MySQL告诉我它不存在。我理解为什么会这样,但这对我没有帮助。

我已尝试根据我在此处阅读的提示Unknown Column In Where Clause将其更改为HAVING is_customer IS NOT NULL,因此:

SELECT
    contacts.*,
    orders.order_id AS is_customer,
    purchases.purchase_id AS is_supplier
FROM contacts
LEFT JOIN orders ON orders.customer_id=contacts.contact_id
LEFT JOIN purchases ON purchases.supplier_id=contacts.contact_id
HAVING is_customer IS NOT NULL
AND contacts.account_id=1
ORDER BY contact_company_name

...并且此查询可以正常工作,只需删除GROUP BY子句即可。显然这会破坏我的结果集。

有人可以帮我解决这个疑问吗?

1 个答案:

答案 0 :(得分:0)

不确定是否一般都是为了回答您自己的问题,但我已经通过阅读此页https://dev.mysql.com/doc/refman/5.0/en/group-by-handling.html来使其工作。

原来使用GROUP BY的语句很好,我只需要重新排列语句的顺序。 GROUP BY位于WHERE之后但位于HAVING之前,如下所示:

SELECT
    contacts.*,
    orders.order_id AS is_customer,
    purchases.purchase_id AS is_supplier
FROM contacts
LEFT JOIN orders ON orders.customer_id=contacts.contact_id
LEFT JOIN purchases ON purchases.supplier_id=contacts.contact_id
AND contacts.account_id=1
GROUP BY contact_id
HAVING is_supplier IS NOT NULL
ORDER BY contact_company_name