3

我正在制作一个我们有电台的音乐播放器。我有一张叫做历史的表。它包含用户喜欢、不喜欢或跳过的歌曲的数据。我们存储一个人喜欢或不喜欢一首歌的所有时间。我们想要获取用户在给定电台中喜欢 (event_type=1) 或不喜欢 (event_type=2) 的所有歌曲的当前快照。

该表具有以下行:

  • id(PK int 自动增量)
  • station_id(FK 整数)
  • song_id(FK 整数)
  • event_type(整数,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;

有没有办法让这个查询在没有内部选择的情况下运行?我很确定如果没有它,它会运行得更快

4

3 回答 3

5

你可以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;
于 2013-04-24T06:37:43.893 回答
3

@Mahmoud Gamal 的答案是正确的,您可能可以摆脱一些不需要的条件。

SELECT h1.song_id, h1.event_type, h1.id 
FROM histories AS h1
INNER JOIN
(
   SELECT MAX(id) AS MaxId
   FROM histories 
   WHERE station_id = 187 
     AND event_type IN (1, 2) 
   GROUP BY song_id
)  AS h2  ON h1.id = h2.maxid
ORDER BY h1.id;
于 2013-04-24T06:55:51.913 回答
0

根据您的描述,答案如下:

SELECT DISTINCT song_id, event_type, id 
FROM histories 
WHERE station_id = 187 
AND (event_type=1 OR event_type=2) 
ORDER BY id

但你一定是出于某种原因在做 MAX - 为什么?

于 2013-04-24T06:38:15.523 回答