Mysql - 具有多个接收ID的动态UNION

时间:2017-06-17 07:46:10

标签: mysql sql mysqli union

如何将这个多个UNION转换为简单查询?

artist_id的数量是动态的。

  • 45,122,95

  • 100,20

  • 89,9449

  • 22,495,700,98

...

(SELECT b.`id`, b.`id`, b.`date`, b.`artist`, b.`title`, b.`photo`
FROM `tags_mp3s` a
INNER JOIN `mp3s` b ON b.`id` = a.`mp3_id` AND a.`artist_id` = 45
ORDER BY b.`date` DESC
LIMIT 5)

UNION ALL

(SELECT b.`id`, b.`id`, b.`date`, b.`artist`, b.`title`, b.`photo`
FROM `tags_mp3s` a
INNER JOIN `mp3s` b ON b.`id` = a.`mp3_id` AND a.`artist_id` = 122
ORDER BY b.`date` DESC
LIMIT 5)

UNION ALL

(SELECT b.`id`, b.`id`, b.`date`, b.`artist`, b.`title`, b.`photo`
FROM `tags_mp3s` a
INNER JOIN `mp3s` b ON b.`id` = a.`mp3_id` AND a.`artist_id` = 95
ORDER BY b.`date` DESC
LIMIT 5)

.....

感谢

1 个答案:

答案 0 :(得分:1)

在MySQL中,您可以使用变量:

SELECT ta.*
FROM (SELECT m.*,
             (@rn := if(@a = t.artist_id, @rn + 1,
                        if(@a := t.artist_id, 1, 1)
                       )
             ) as rn
      FROM tags_mp3s t INNER JOIN
           mp3s m
           ON m.id = t.mp3_id CROSS JOIN
           (SELECT @rn := 0, @a := -1) params
      WHERE t.artist_id IN (. . . )
      ORDER BY t.artist_id, m.date DESC
     ) ta
WHERE rn <= 5;