MySQL Group by,Order by Two Columns

时间:2017-12-12 09:22:49

标签: php mysql greatest-n-per-group

我想获得每部电影的最后一集名称

表格结构:

+---------+------------+---------------+
|     id  |  movie_id  |  episode_name |
+---------+------------+---------------+
|      1  |         1  |             1 |
|      2  |         1  |             2 |
|      3  |         1  |             3 |
|      4  |         2  |             1 |
|      5  |         3  |             1 |
|      6  |         2  |             2 |
|      7  |         1  |             4 |
|      8  |         2  |             3 |
|      9  |         4  |             1 |
+---------+------------+---------------+

查询1:

SELECT * FROM episode
group by movie_id
order by id desc, episode_name desc LIMIT 10

查询2:

SELECT * FROM episode
WHERE movie_id IN (select movie_id from episode group by movie_id)
group by movie_id
order by episode_name desc

但输出不是我想要的,也许我做错了方式

+--------+------------+---------------+
|  id    |  movie_id  |  episode_name |
+--------+------------+---------------+
|     9  |         4  |             1 |
|     5  |         3  |             1 |
|     4  |         2  |             1 |
|     1  |         1  |             1 |
+--------+------------+---------------+

我想要的结果是:

+---------+------------+---------------+
|     id  |  movie_id  |  episode_name |
+---------+------------+---------------+
|      9  |         4  |             1 |
|      8  |         2  |             3 |
|      7  |         1  |             4 |
|      5  |         3  |             1 |
+---------+------------+---------------+

2 个答案:

答案 0 :(得分:4)

这是一个非常常见的问题,我们可以通过将episode表连接到子查询来处理MySQL,该子查询可以找到每部电影的最新剧集。这种方法为我们提供了完整匹配的最新记录,包括id列,然后我们可以使用它来订购结果集。

SELECT e1.*
FROM episode e1
INNER JOIN
(
    SELECT movie_id, MAX(episode_name) AS max_episode_name
    FROM episode
    GROUP BY movie_id
) e2
    ON e1.movie_id = e2.movie_id AND
       e1.episode_name = e2.max_episode_name
ORDER BY
    e1.id DESC;

Demo

答案 1 :(得分:2)

如果您只想要最后一个episode_name,并且如果我遵循表格的逻辑,您可以尝试在SELECT查询中使用MAX(),这样您只能获得列的最终结果" episode_name&# 34; (模式信息here

SELECT id, movie_id, MAX(episode_name) 
FROM table GROUP BY movie_id 
ORDER BY id DESC

这是你在找什么?