当前位置:  开发笔记 > 后端 > 正文

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

如何解决《MySQL-在WHERE子句中使用COUNT(*)》经验,为你挑选了7个好方法。

我试图在MySQL中完成以下内容(请参阅pseudo代码)

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

有没有办法在不使用WHERE子句中的(SELECT ...)的情况下执行此操作,因为这看起来像是浪费资源.



1> Ali Ersöz..:

试试这个;

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


+1这是*总是*他们不打扰在sql课程或书籍上正确教导的条款,并且通常知道编码器已经超出新手级别的标志.

2> Greg..:

我不确定你要做什么......也许是这样的

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



3> Winston Smit..:
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



4> sme..:

尝试

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



5> Máťa - Stito..:

只是没有条款的学术版:

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



6> 小智..:

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;



7> zzapper..:

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

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

推荐阅读
落单鸟人
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有