如何将这个多个UNION转换为简单查询?
artist_id
的数量是动态的。
或
或
或
...
(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)
.....
感谢
答案 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;