1. 程式人生 > >mysql 統計一個表中各類別的數目,並儲存

mysql 統計一個表中各類別的數目,並儲存

  1. 下圖為使用者聽歌記錄表recordTime:
    這裡寫圖片描述
  2. 下圖為歌曲表music:
    這裡寫圖片描述
  3. 現在需要計算每首歌被聽數,並將其儲存到歌曲表中,mysql語句為:
UPDATE music D
  LEFT JOIN (SELECT 
        B.musicId,
                count(*) AS s_sum
           FROM recordTime B
          GROUP BY B.musicId) C
    ON (C.musicId = D.musicId)
   SET D.listenTimes = c.s_sum
 WHERE D.musicId = 
       (
         SELECT
E.id FROM ( SELECT DISTINCT a.musicId AS id FROM recordTime A ) E WHERE E.id = D.musicId )