我有以下sql语句:
SELECT
u.email,
sum(completed_on > (now() - interval 7 day)),
sum(completed_on > (now() - interval 30 day)),
count(*)
FROM mturk_flush f JOIN auth_user u ON f.completed_by_id=u.id
WHERE completed_by_id IS NOT NULL
GROUP BY completed_by_id
HAVING 3 != 0
ORDER BY 3 DESC
请注意,以下确实有效:
HAVING sum(completed_on > (now() - interval 30 day)) != 0
是否可以使用别名或索引来引用它?
答案 0 :(得分:2)
与Order By
子句不同,Having
不适用于列号。来自Docs:
[HAVING where_condition] [ORDER BY {col_name | expr | position}
现在,我建议您不要使用列号,即使使用Order By
也不要使用。它易于出错,并降低了代码的清晰度,并为以后的维护人员带来了可读性。
您可以改为在Group By
,Order By
和Having
子句中定义别名和use them。
SELECT
u.email,
sum(completed_on > (now() - interval 7 day)) AS sum_7day_diff,
sum(completed_on > (now() - interval 30 day)) AS sum_30day_diff,
count(*)
FROM mturk_flush f JOIN auth_user u ON f.completed_by_id=u.id
WHERE completed_by_id IS NOT NULL
GROUP BY completed_by_id
HAVING sum_30day_diff != 0
ORDER BY sum_30day_diff DESC