我收到具体查询:
SELECT *
FROM stats
WHERE mod_name = 'module'
GROUP BY domain
ORDER BY addition_date DESC
我想检索每个域的最新值。我知道有一个域 x.com 值,日期为 2014-02-19。
但是,此查询返回日期为:2014-01-06 的行
这是非常简单的查询...为什么它不按域分组而只采用最新值? 我错过了什么吗?
最佳答案
order by
发生在group by
之后。这就是您的查询不起作用的原因。这是一种获得您想要的东西的方法:
SELECT s.*
FROM stats s
WHERE mod_name = 'module' and
not exists (select 1
from stats s2
where s2.mod_name = s.mod_name and
s2.addition_date > s.addition_date
)
ORDER BY addition_date DESC;
要获得最佳性能,请在 stats(mod_name,addition_date)
上创建索引。
关于mysql - 为什么 MySQL 查询不返回最新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21975790/