在数字查询中使用Have子句

时间:2018-11-04 21:11:32

标签: mysql sql

我有以下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

是否可以使用别名或索引来引用它?

1 个答案:

答案 0 :(得分:2)

Order By子句不同,Having不适用于列号。来自Docs

[HAVING where_condition]
[ORDER BY {col_name | expr | position}

现在,我建议您不要使用列号,即使使用Order By也不要使用。它易于出错,并降低了代码的清晰度,并为以后的维护人员带来了可读性。

您可以改为在Group ByOrder ByHaving子句中定义别​​名和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