3

ステーションのある音楽プレーヤーを作成しています。履歴と呼ばれるテーブルがあります。ユーザーが好き、嫌い、スキップした曲に関するデータがあります。私たちは、人が曲を気に入った、または気に入らなかった回数を常に保存します。特定のステーションでユーザーが好き (event_type=1) または嫌い (event_type=2) にしたすべての曲の現在のスナップショットを取得したいと考えています。

テーブルには次の行があります。

  • id(PK int 自動インクリメント)
  • 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;

内部選択なしでこのクエリを実行する方法はありますか? これがなければ、これはずっと速く実行されると確信しています

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 に答える
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 に答える