我正在尝试在 MySQL 中完成以下操作(参见
pseudo
代码)
SELECT DISTINCT gid
FROM `gd`
WHERE COUNT(*) > 10
ORDER BY lastupdated DESC
有没有办法在 WHERE 子句中不使用 (SELECT...) 来做到这一点,因为这看起来像是在浪费资源。
试试这个;
select gid
from `gd`
group by gid
having count(*) > 10
order by lastupdated desc
我不确定你想做什么……也许是这样的
SELECT gid, COUNT(*) AS num FROM gd GROUP BY gid HAVING num > 10 ORDER BY lastupdated DESC
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
只有学术版没有条款:
select *
from (
select gid, count(*) as tmpcount from gd group by gid
) as tmp
where tmpcount > 10;
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;
试试
SELECT DISTINCT gid
FROM `gd`
group by gid
having count(*) > 10
ORDER BY max(lastupdated) DESC
COUNT(*)只能与HAVING一起使用,必须在GROUP BY之后使用 statement 请看下面的例子:
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
-- 寻找缺失半小时记录的气象站
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;
-- 带有 where .. in .. select 的 yapiskan 变体
我认为你不能用
count()
添加where
。现在明白为什么....
where
与 having
不同,having
表示您正在处理或处理组和计数的相同工作,它也在处理整个组,
现在如何算作整个团队工作
创建一个表并输入一些 id,然后使用:
select count(*) from table_name
你会发现total values表示它代表了一些组!所以
where
确实添加了 count()
;
SELECT DISTINCT gid
FROM `gd`
GROUP BY gid
HAVING COUNT(gid) > 10
ORDER BY lastupdated DESC;