我有一张桌子包含歌曲。我想选择3首最喜欢的歌曲和3首随机出现的歌曲,它们不在第一个查询中。
song 6, song 8, song 5 then *whatever song*,*whatever song*,*whatever song*
这是我尝试但无法使用的内容:
SELECT a.`song_id`, a.`name`, a.liked, b.song_id
FROM `song` AS a,
(SELECT song_id FROM song ORDER BY liked DESC LIMIT 3) as b
WHERE a.song_id <> b.song_id LIMIT 3
SELECT
a.`song_id`, a.`name`, a.liked, b.ids
FROM
`song` AS a,
(SELECT substring_index(GROUP_CONCAT(DISTINCT song_id ORDER BY liked DESC SEPARATOR ','), ',', 3) as ids FROM song) as b
WHERE
a.song_id not in(b.ids)
我正在使用MariaDB 10.1.29,它与子查询或LIMIT
子句中的WITH
不兼容。
答案 0 :(得分:1)
在MariaDb 10.2和MySql 8.0中使用带有LIMIT的两个CTE's
第二个CTE随机执行,而没有从第一个CTE中选择
WITH TOP3SONGS AS
(
SELECT *
FROM song
ORDER BY liked DESC
LIMIT 3
),
RANDOM3SONGS AS
(
SELECT *
FROM song
WHERE song_id NOT IN (select song_id from TOP3SONGS)
ORDER BY rand()
LIMIT 3
)
SELECT *
FROM TOP3SONGS
UNION ALL
SELECT *
FROM RANDOM3SONGS;
这在MySql 5.6中有效,因此很有可能也在MariaDb 10.1.29中
(我无法访问10.1,因此无法验证)
这次使用左连接到top3。
并按顺序将top3置于限制6之前的随机数之上。
SELECT song.*
FROM song
LEFT JOIN
( SELECT song_id, liked
FROM song
ORDER BY liked DESC
LIMIT 3
) top3songs ON top3songs.song_id = song.song_id
ORDER BY top3songs.liked DESC, RAND()
LIMIT 6;
对 db <>小提琴here
的测试答案 1 :(得分:0)
您应该将其拆分为两个,然后合并结果: 首先查询以选择前3个:
SELECT song_id FROM song ORDER BY liked DESC LIMIT 3
第二次查询选择随机三首,不包括上面选择的歌曲:
SELECT song_id FROM song WHERE song_id NOT IN (
SELECT song_id FROM song ORDER BY liked DESC LIMIT 3
) ORDER BY RAND() LIMIT 3
现在在一起:
SELECT song_id FROM song ORDER BY liked DESC LIMIT 3
UNOION
SELECT song_id FROM song WHERE song_id NOT IN (
SELECT song_id FROM song ORDER BY liked DESC LIMIT 3
) ORDER BY RAND() LIMIT 3
答案 2 :(得分:0)
目前我只安装了MariaDB 10.3,但是我在较旧的MySQL 4.1上尝试了以下语法,并且都返回了相同的结果。
SELECT * FROM (
(SELECT * FROM song ORDER BY liked DESC LIMIT 3) UNION
(SELECT A.* FROM song A LEFT JOIN (SELECT * FROM song ORDER BY liked DESC LIMIT 3) B ON A.song_id=B.song_id
WHERE B.song_id IS NULL ORDER BY RAND() LIMIT 3)) S ORDER BY liked DESC;