sqlite按随机组排序

时间:2015-05-12 20:42:05

标签: sql sqlite

我有一张包含曲目和专辑列的歌曲表,我想以随机的专辑顺序获取它们。即,在每张专辑中,歌曲将被分类,但专辑将以随机顺序排列。

例如,如果表格为:

-----------------
| track | album |
-----------------
| 1     | a     |
| 2     | a     |
| 3     | a     |
| 1     | b     |
| 2     | b     |
| 1     | c     |
| 2     | c     |
-----------------

比可能的输出

-----------------
| track | album |
-----------------
| 1     | b     |
| 2     | b     |
| 1     | c     |
| 2     | c     |
| 1     | a     |
| 2     | a     |
| 3     | a     |
-----------------

可以使用单个sqlite查询吗?

2 个答案:

答案 0 :(得分:3)

首先,您需要随机订购相册,然后选择曲目。

with tt as (
  select distinct album from t order by random()
)
select t.track, tt.album 
from tt left join t on t.album = tt.album
order by tt.rowid, t.track
;

请参阅Sqlfiddle

答案 1 :(得分:0)

为了达到预期的顺序,我必须在MrSimpleMind的答案中添加一个订单:

WITH albums AS (SELECT DISTINCT album FROM songs ORDER BY RANDOM()) 
SELECT songs.* FROM albums
LEFT JOIN songs
ON songs.album = albums.album
ORDER BY albums.rowid, songs.track