考虑以下问题:
SELECT domain, done FROM tasks WHERE 1 GROUP BY domain
显然我可以用MAX(完成)返回“完成”的最大值,但是如何让它返回整行呢?
在我所处的情况下,我有一个包含以下行的表:
domain = somedomain.com, done = 12:27:39, somecolumn = pink
domain = somedomain.com, done = 13:27:39, somecolumn = blue
domain = somedomain.com, done = 14:27:39, somecolumn = orange
domain = anotherdomain.com, done = 07:27:39, somecolumn = orange
domain = anotherdomain.com, done = 09:27:39, somecolumn = pie
使用上面的查询,它返回以下2行:
domain = somedomain.com, done = 13:27:39, somecolumn = blue
domain = anotherdomain.com, done = 09:27:39, somecolumn = pie
我需要返回这两行:
domain = somedomain.com, done = 14:27:39, somecolumn = blue
domain = anotherdomain.com, done = 09:27:39, somecolumn = pie
感谢帮助:)。
答案 0 :(得分:4)
最简单的一个:
SELECT done,somecolumn FROM tasks ORDER BY done DESC LIMIT 1;
对于更复杂的查询,可能需要左连接或子查询,但这个很简单。
对于它,如果你确实需要其他数据:
(1)NOT EXISTS:
SELECT a.*
FROM tasks a
WHERE NOT EXISTS(
SELECT * FROM tasks b
WHERE b.domain = a.domain AND b.done > a.done);
(2)LEFT JOIN
SELECT a.*
FROM tasks a
LEFT JOIN tasks b
ON b.domain = a.domain AND b.done > a.done
WHERE b.id IS NULL;
(3)ROWNUMBER()喜欢:
SELECT numbered.*
FROM (
SELECT
@row := IF(@old_domain = domain,@row + 1,1) as rownumber,
@old_domain := domain as domain,
done,
somecolumn
FROM tasks
JOIN (SELECT @old_domain:=0,@row:=0) void
ORDER BY domain ASC, done DESC
) numbered
WHERE numbered.rownumber = 1;
哪一个会给你带来更好的性能取决于数据集,所以我只是测试它们。
答案 1 :(得分:1)
SELECT * FROM tasks WHERE done = (SELECT Max(done) FROM tasks)
答案 2 :(得分:1)
select
*
from
tasks
where
`done`=(select max(`done`) from tasks)