我有一个MySQL表,我有一个id作为来自另一个表的外键。此id不是此表唯一的,因此我可以拥有许多具有相同ID的记录。 我需要找出在这个表中看到哪些id最少的时间并拉出包含它们的列表。
例如,如果我有5条id = 1的记录,3条id = 2的记录和3条id = 3的记录,我想只提取ID 2& 3.但是,表格中的数据经常变化,因此我不知道在任何给定时刻最小值是多少。如果我使用两个查询但是我只想用一个查询,那么任务就很简单了。这就是我所拥有的:
SELECT id
FROM table
GROUP BY id
HAVING COUNT(*) = MIN(SELECT COUNT(*) FROM table GROUP BY id)
如果我用COUNT(*)= 3代替,那么结果会出现但是使用上面的查询会给我一个MIN没有正确使用的错误。有什么提示吗?
答案 0 :(得分:4)
我会尝试:
SELECT id
FROM table
GROUP BY id
HAVING COUNT(*) = (SELECT COUNT(*) FROM table GROUP BY id ORDER BY COUNT(*) LIMIT 1);
这样就可以从ascendent order中的计数集中选择第一行。
答案 1 :(得分:2)
select
子句中需要加倍having
:
SELECT id
FROM table
GROUP BY id
HAVING COUNT(*) = (SELECT MIN(cnt) FROM (SELECT COUNT(*) as cnt FROM table GROUP BY id) t);
答案 2 :(得分:1)
您需要GROUP BY
生成一组分组值,并选择其他选择以获取该组中的MIN
值,然后才能将其与
SELECT * FROM table GROUP BY id
HAVING COUNT(*) =
(SELECT MIN(X.CNT) AS M FROM(SELECT COUNT(*) CNT FROM table GROUP BY id) AS X)
答案 3 :(得分:1)
MIN()
聚合函数用于获取列,而不是查询。所以,我认为有两种方法可以解决这个问题:
第一种选择:
select id
from yourTable
group by id
having count(id) = (
select min(c) from (
select count(*) as c from yourTable group by id
) as a
)
第二种选择:
set @minCount = (
select min(c) from (
select count(*) as c from yourTable group by id
) as a
);
select id
from yourTable
group by id
having count(*) = @minCount;