MySQL-在WHERE子句中使用COUNT(*)


157

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

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

有没有一种方法可以在WHERE子句中不使用(SELECT ...),因为这似乎浪费资源。

Answers:


264

试试这个;

select gid
from `gd`
group by gid 
having count(*) > 10
order by lastupdated desc

37
+1为拥有这始终是他们不愿意在sql课程或书籍上正确教书的子句,并且通常都知道编码器已经超越了新手级别。
Cruachan

如果您尝试将COUNT()用作布尔OR表达式的一部分怎么办?例如AND ((stock = 1 OR quantity > 0) OR (COUNT(v.id) > 0)
nnyby 2011年

我想通了..您可以像这样添加到HAVING子句:HAVING variations > 0 OR (stock = 1 OR quantity > 0)
nnyby 2011年

28

我不确定您要做什么...也许类似

SELECT gid, COUNT(*) AS num FROM gd GROUP BY gid HAVING num > 10 ORDER BY lastupdated DESC

1
MSSQL为给出“无效的列名”解析错误num。无论如何,+ 1都是干净的语法(可能是我的设置,还是ms ...嗯……)。
samis

为选择中的所有列提供别名。
阿迪尔·哈利勒

17
SELECT COUNT(*)
FROM `gd`
GROUP BY gid
HAVING COUNT(gid) > 10
ORDER BY lastupdated DESC;

编辑(如果您只想要这些小物品):

SELECT MIN(gid)
FROM `gd`
GROUP BY gid
HAVING COUNT(gid) > 10
ORDER BY lastupdated DESC

谢谢乔,但是这返回了COUNT()-我希望返回所有COUNT(*)大于10的女

1
那里没有Min()的需要。
AliErsöz08年

14

尝试

SELECT DISTINCT gid
FROM `gd`
group by gid
having count(*) > 10
ORDER BY max(lastupdated) DESC

14

仅有条款的学术版本:

select *
from (
   select gid, count(*) as tmpcount from gd group by gid
) as tmp
where tmpcount > 10;

13

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

-搜索缺少半小时记录的气象站

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的变体,其中..在..中选择


1

我想你不能添加count()使用where。现在看看为什么....

where不相同havinghaving表示您正在从事小组工作或从事同等的工作,它也涉及整个小组,

现在如何计算整个团队

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

select count(*) from table_name

您会发现总值意味着它表示某个组!所以where不添加count();


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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.