这是我的MySQL查询及其返回的内容:
SELECT email, COUNT(*) AS num
FROM collectors_users
WHERE subscribed != 'NO'
AND lastLogin IS NULL
GROUP BY email
ORDER BY dateadded DESC;
我只想返回num>的结果1.我试图像这样更改我的查询,但它没有说明num
不是公认的列:
SELECT email, COUNT(*) AS num
FROM collectors_users
WHERE subscribed != 'NO'
AND lastLogin IS NULL
AND num > 1
GROUP BY email
ORDER BY dateadded DESC;
如何在num>处返回结果? 1?
答案 0 :(得分:3)
在GROUP BY子句之后,在ORDER BY子句之前添加:
HAVING COUNT(*) > 1
在HAVING
子句之前准备好所有行之后,LIMIT
子句几乎在执行计划中最后应用。这对于在访问行时无法检查的条件非常有用,但仅在访问了行之后才会检查,例如像COUNT(*)这样的聚合函数,尽管它可以用于非聚合。 / p>
答案 1 :(得分:0)
使用HAVING
子句。或者另一种方式:
SELECT * FROM
(SELECT email, COUNT(*) AS num
FROM collectors_users
WHERE subscribed != 'NO'
AND lastLogin IS NULL
GROUP BY email
ORDER BY dateadded DESC;
) T
WHERE num>1
答案 2 :(得分:0)
我认为你应该使用HAVING
SELECT email, COUNT(*) AS num
FROM collectors_users
WHERE subscribed != 'NO'
AND lastLogin IS NULL
GROUP BY email
ORDER BY dateadded DESC
HAVING COUNT(*) > 1;
这个问题可以帮助您理解为什么HAVING
而不是WHERE
答案 3 :(得分:0)
SELECT email, COUNT(*) as num
FROM collectors_users
WHERE subscribed != 'NO'
AND lastLogin IS NULL
GROUP BY email
HAVING COUNT(*) > 1
答案 4 :(得分:0)
您可以使用Having子句。
SELECT email, COUNT(*) AS num
FROM collectors_users
WHERE subscribed != 'NO'
AND lastLogin IS NULL
GROUP BY email
HAVING count(*) > 1
ORDER BY dateadded DESC;