我正在制作一个音乐播放器,我们有电台.我有一张名为历史的表.它包含用户喜欢,不喜欢或跳过的歌曲的数据.我们存储一个人喜欢一首歌或不喜欢它的所有时间.我们希望得到用户在给定电台中喜欢(event_type = 1)或不喜欢(event_type = 2)的所有歌曲的当前快照.
该表包含以下行:
id (PK int autoincrement)station_id (FK int)song_id (FK int)event_type (int,1,2或3)这是我的查询:
SELECT song_id, event_type, id
FROM histories
WHERE id IN (SELECT MAX(id) AS id
FROM histories
WHERE station_id = 187
AND (event_type=1 OR event_type=2)
GROUP BY station_id, song_id)
ORDER BY id;
Run Code Online (Sandbox Code Playgroud)
有没有办法让这个查询在没有内部选择的情况下运行?我很确定如果没有它,它会运行得更快
你可以JOIN改用.像这样的东西:
SELECT h1.song_id, h1.event_type, h1.id
FROM histories AS h1
INNER JOIN
(
SELECT station_id, song_id, MAX(id) AS MaxId
FROM histories
WHERE station_id = 187
AND event_type IN (1, 2)
GROUP BY station_id, song_id
) AS h2 ON h1.station_id = h2.station_id
AND h1.song_id = h2.song_id
AND h1.id = h2.maxid
ORDER BY h1.id;
Run Code Online (Sandbox Code Playgroud)