我正在尝试在MySQL中完成以下操作(请参阅pseudo
代码)
SELECT DISTINCT gid
FROM `gd`
WHERE COUNT(*) > 10
ORDER BY lastupdated DESC
有没有办法在WHERE子句中不使用(SELECT ...)来执行此操作,因为这似乎是浪费资源。
答案 0 :(得分:245)
试试这个;
select gid
from `gd`
group by gid
having count(*) > 10
order by lastupdated desc
答案 1 :(得分:25)
我不确定你要做什么...也许像是
SELECT gid, COUNT(*) AS num FROM gd GROUP BY gid HAVING num > 10 ORDER BY lastupdated DESC
答案 2 :(得分:15)
SELECT COUNT(*)
FROM `gd`
GROUP BY gid
HAVING COUNT(gid) > 10
ORDER BY lastupdated DESC;
编辑(如果你只想要gids):
SELECT MIN(gid)
FROM `gd`
GROUP BY gid
HAVING COUNT(gid) > 10
ORDER BY lastupdated DESC
答案 3 :(得分:14)
试
SELECT DISTINCT gid
FROM `gd`
group by gid
having count(*) > 10
ORDER BY max(lastupdated) DESC
答案 4 :(得分:12)
没有条款的学术版:
select *
from (
select gid, count(*) as tmpcount from gd group by gid
) as tmp
where tmpcount > 10;
答案 5 :(得分:7)
A WHERE子句中不能有聚合函数(例如COUNT,MAX等)。因此我们改用HAVING子句。因此整个查询将类似于:
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value;
答案 6 :(得分:6)
- 搜索缺少半小时记录的气象站
SELECT stationid
FROM weather_data
WHERE `Timestamp` LIKE '2011-11-15 %' AND
stationid IN (SELECT `ID` FROM `weather_stations`)
GROUP BY stationid
HAVING COUNT(*) != 48;
- yapiskan的变体与where .. in .. select
答案 7 :(得分:1)
我认为您无法使用count()
添加where
。现在明白为什么......
where
与having
不同,having
表示您正在工作或处理群体和同样的计数工作,它也在处理整个群体,
现在如何统计它是整个群体的工作
创建一个表并输入一些id然后使用:
select count(*) from table_name
你会发现总值意味着它表示某个群体!所以where
添加了count()
;
答案 8 :(得分:1)
COUNT(*)仅可与HAVING一起使用,并且必须在GROUP BY之后使用 声明请找到以下示例:
SELECT COUNT(*), M_Director.PID FROM Movie
INNER JOIN M_Director ON Movie.MID = M_Director.MID
GROUP BY M_Director.PID
HAVING COUNT(*) > 10
ORDER BY COUNT(*) ASC