如何组合GROUP BY,ORDER BY和HAVING

时间:2011-07-18 14:14:07

标签: mysql sql

如何正确组合此声明。

SELECT *, COUNT(*)
FROM user_log
GROUP BY Email
ORDER BY UpdateDate DESC
HAVING COUNT(*) > 1

让我知道

3 个答案:

答案 0 :(得分:53)

ORDER BY永远是最后的......

但是,您需要选择 ACTUALLY WANT 的字段,然后只选择那些并按其分组。 SELECT *GROUP BY Email会为Email以外的所有字段提供 RANDOM VALUES 。大多数RDBMS甚至不允许你这样做,因为它创建的问题,但MySQL是例外。

SELECT Email, COUNT(*)
FROM user_log
GROUP BY Email
HAVING COUNT(*) > 1
ORDER BY UpdateDate DESC

答案 1 :(得分:-1)

您的代码应在WHILEgroup by之前包含having

SELECT Email, COUNT(*)

FROM user_log

WHILE Email IS NOT NULL

GROUP BY Email

HAVING COUNT(*) > 1

ORDER BY UpdateDate DESC

答案 2 :(得分:-2)

使用分组依据,按顺序排序......

Select Attitude ,count(*) from Person
group by person
HAving PersonAttitude='cool and friendly'
Order by PersonName.