我需要编写一个查询,我需要从表中检索数据。
Table
===================================
ID | userID | Status | date |
===================================
1 3333 Queued xxxx
2 4444 Queued yyyy
3 5555 Finished zzzzz
5 6666 Queued iiiii
6 7777 Queued kkkkk
现在我只想在status =“Queued”且status =“Queued”的行超过2且具有最新ID的行时才检索该行。即我希望答案是ID = 6
我尝试使用以下查询
select * from t1 where status = "Queued" GROUP BY status HAVING count(status) > 2 ORDER BY ID DESC limit 1
答案 0 :(得分:5)
您可以使用子查询。问题是订购是在分组之前完成的。这样的事情应该有效:
select * from t1 where ID = (select max(id) from t1 where status = "Queued" group by status having count(status) > 2)
答案 1 :(得分:0)
以下查询应该解决它:
select * from t1
where id = (select max(id) from t1 where Status = 'Queued' group by Status having count(1)>2);
答案 2 :(得分:0)
这种变体也是可能的 -
SELECT * FROM (
SELECT * FROM t1 WHERE status = 'Queued' ORDER BY ID DESC) t
GROUP BY status HAVING count(status) > 2;