在 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` = ?
可以以某种方式将其简化为一个查询吗?
在 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` = ?
可以以某种方式将其简化为一个查询吗?
只需使用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;
自 MariaDB 10.2 引入Common Table Expressions以来,可以使用另一种编写此查询的方法。使用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;