mysql查询-按日期和id过滤

gudnpqoy  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(520)

我有一张table,我想得到:

ID  Name    Stock   Code    Date
<---------------------------------------------->
123 GAME_0011     1     WK1 2018-11-20 16:12:16
120 GAME_0088     212   WK1 2018-11-20 19:32:13
109 GAME_0088     21    WK1 2018-11-20 19:32:13
101 GAME_0088     20    WK1 2018-11-20 14:00:41
105 GAME_0011     1     WK1 2018-11-20 14:00:41
102 GAME_0088     2     WK1 2018-11-20 14:00:41

结果将按名称、代码和它们中每一个的最大 date 字段,如果日期相同,则按 id 也是:

ID  Name    Stock   Code    Date
<---------------------------------------------->
120 GAME_0088     212   WK1 2018-11-20 19:32:13
123 GAME_0011     1     WK1 2018-11-20 16:12:16

我的问题是:

SELECT *
FROM games
WHERE name IN ('GAME_0088', 'GAME_0011')
AND code IN ('WK1')
AND date IN (SELECT max(date) FROM stocks GROUP BY name)
ORDER BY id desc

但结果是:

ID  Name    Stock   Code    Date
<---------------------------------------------->
123 GAME_0011   1   WK1 2018-11-20 16:12:16
109 GAME_0088   21  WK1 2018-11-20 19:32:13

怎么了?我怎么也能按最大id过滤呢?

xqnpmsa8

xqnpmsa81#

在派生表中,可以获得 ID 对于一组特定的 name 以及 code . 加入到 games 表中使用此信息获取对应于最大日期的行。

SELECT g.*
FROM games AS g 
JOIN 
( SELECT name, code, MAX(ID) AS max_id
  FROM games 
  GROUP BY name, code
) AS dt ON dt.name = g.name AND 
           dt.code = g.code AND 
           dt.max_id = g.ID 
WHERE g.name IN ('ACK1134', 'ACK1159')
  AND g.code IN ('CD23')
ORDER BY g.ID desc

相关问题