我正在尝试在 MySQL 中完成以下操作(请参阅pseudo
代码)
SELECT DISTINCT gid
FROM `gd`
WHERE COUNT(*) > 10
ORDER BY lastupdated DESC
有没有办法在 WHERE 子句中不使用 (SELECT...) 来做到这一点,因为这似乎是一种资源浪费。
我正在尝试在 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;
尝试
SELECT DISTINCT gid
FROM `gd`
group by gid
having count(*) > 10
ORDER BY max(lastupdated) DESC
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;
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
-- 搜索缺少半小时记录的气象站
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
我认为你不能添加count()
with where
。现在看看为什么....
where
不一样having
,having
意味着你正在工作或处理小组和计数相同的工作,它也在处理整个小组,
现在如何计算它作为一个整体工作
创建一个表并输入一些ID,然后使用:
select count(*) from table_name
您会发现总值意味着它表示某个组!where
添加count()
;也是如此