1

在 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` = ?

可以以某种方式将其简化为一个查询吗?

4

2 回答 2

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;
于 2017-07-15T20:24:59.540 回答
1

自 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;
于 2017-07-18T16:37:50.367 回答