181

我正在尝试在 MySQL 中完成以下操作(请参阅pseudo代码)

SELECT DISTINCT gid
FROM `gd`
WHERE COUNT(*) > 10
ORDER BY lastupdated DESC

有没有办法在 WHERE 子句中不使用 (SELECT...) 来做到这一点,因为这似乎是一种资源浪费。

4

9 回答 9

307

尝试这个;

select gid
from `gd`
group by gid 
having count(*) > 10
order by lastupdated desc
于 2008-11-19T12:52:53.303 回答
30

我不确定你想要做什么......也许像

SELECT gid, COUNT(*) AS num FROM gd GROUP BY gid HAVING num > 10 ORDER BY lastupdated DESC
于 2008-11-19T12:52:55.470 回答
20
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
于 2008-11-19T12:52:12.197 回答
17

只是没有条款的学术版本:

select *
from (
   select gid, count(*) as tmpcount from gd group by gid
) as tmp
where tmpcount > 10;
于 2013-09-10T12:25:29.150 回答
15

尝试

SELECT DISTINCT gid
FROM `gd`
group by gid
having count(*) > 10
ORDER BY max(lastupdated) DESC
于 2008-11-19T12:52:59.963 回答
15

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;
于 2016-01-20T09:11:21.507 回答
7

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
于 2019-09-05T13:45:20.733 回答
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

于 2011-11-16T13:22:00.343 回答
1

我认为你不能添加count()with where。现在看看为什么....

where不一样havinghaving意味着你正在工作或处理小组和计数相同的工作,它也在处理整个小组,

现在如何计算它作为一个整体工作

创建一个表并输入一些ID,然后使用:

select count(*) from table_name

您会发现总值意味着它表示某个组!where添加count();也是如此

于 2012-04-05T06:32:27.480 回答