4

如何为 MySQL 中的每个组选择第一行(按日期时间排序)?

我试过了,我得到了这个:

SELECT *
FROM `cats`
WHERE `war_id` = 0 
AND `eyes_color` = 'green' 
AND `id` IN
    (SELECT `id` FROM
        (SELECT * FROM `cats` ORDER BY `date_last_fought` DESC) AS t
    GROUP BY `war_id`, `n_of_medals`)

它有点工作,但我不确定它是否是有史以来最好的。

你认为我可以简化这个吗?

4

2 回答 2

5

我试图简化成这个......

SELECT * FROM `cats`
inner join (select * from cats 
        WHERE `warid` = 1 AND `color` = 'green' 
        order by orderDate desc) a 
        on (cats.id=a.id)
group by cats.warId;


你可以在这里看到http://sqlfiddle.com/#!2/55f5b/5
但我不确定它是否比你的查询更好,...从 EXPLAIN 阅读和行动仍然成为我的作业:D

ID  SELECT_TYPE TABLE      TYPE    POSSIBLE_KEYS    KEY   KEY_LEN   REF    ROWS EXTRA
1   PRIMARY     <derived2> ALL     (null)          (null) (null)    (null)   2  Using temporary; Using filesort
1   PRIMARY     cats       eq_ref  PRIMARY         PRIMARY  4       a.id     1  
2   DERIVED     cats       ALL     (null)          (null) (null)    (null)   6  Using filesort

并添加索引将使其更快

于 2013-02-16T21:32:40.857 回答
0

这是我的解决方案:

SELECT * FROM `cats` c
JOIN (
    SELECT `war_id`, `n_of_medals`, MAX(`date_last_fought`) date_last_fought
    FROM `cats` 
    WHERE `war_id` = 0 
    AND `eyes_color` = 'green' 
    GROUP BY `war_id`, `n_of_medals` 
) c_summary ON c_summary.war_id = c.war_id
AND c_summary.n_of_medals = c.n_of_medals 
AND c_summary.date_last_fought = c.date_last_fought
ORDER BY c.`date_last_fought` DESC;

http://sqlfiddle.com/#!2/05bcb/2

于 2013-05-17T01:23:30.757 回答