在MariaDB / MySQL中我有一个这样的表:
带有table (key1, key2, date)
的 INDEX(key1, key2)
现在我想拿最早的条目:
SELECT * FROM `table` ORDER BY `date` ASC LIMIT 1
最后所有与第一个查询中的key1
和key2
匹配的条目:
SELECT * FROM `table` WHERE `key1` = ? AND `key2` = ?
这可以以某种方式简化为一个查询吗?
答案 0 :(得分:3)
只需使用join
:
select t.*
from `table` t join
(select t.*
from `table` t
order by `date` asc
limit 1
) tt
on t.key1 = tt.key1 and t.key2 = tt.key2;
答案 1 :(得分:1)
由于MariaDB 10.2引入了公用表表达式,因此可以使用另一种编写此查询的方法。使用WITH语法,查询如下所示:
WITH t_oldest AS (SELECT * FROM `table` ORDER BY `date` asc LIMIT 1)
SELECT t.* FROM `table` AS t,t_oldest
WHERE t.key1 = t_oldest.key1 AND t.key2 = t_oldest.key2;