DECLARE @NumItems int = 100;
DECLARE @minValue int;
DECLARE @maxValue int;
SELECT @minValue = min(id), @maxValue = max(id) from [TABLE];
DECLARE @range int = @maxValue+1 - @minValue;
with cte (n) as (
select 1 union all
select n+1 from cte
where n < @NumItems
)
select cast( @range * rand(cast(newid() as varbinary(100))) + @minValue as int) tp
into #Nt
from cte;
select * from #Nt ntt
inner join [TABLE] i on i.id = ntt.tp;
drop table #Nt;
| id | artist | title |
|----|---------------------------------|------------------------------------|
| 1 | Miyagi & Эндшпиль ft. Рем Дигга | I Got Love |
| 2 | HAIM | Don't Save Me (Cyril Hahn Remix) |
| 3 | 2Pac ft. DMX | Rise Of A Champion (GalilHD Remix) |
| 4 | Ed Sheeran & Passenger | No Diggity (Kygo Remix) |
| 5 | JP Cooper ft. Mali-Koa | All This Love |
甲骨文
在Oracle上,你需要使用DBMS_RANDOM.VALUE函数,如下面的例子所示:
SELECT
artist||' - '||title AS song
FROM song
ORDER BY DBMS_RANDOM.VALUE
当在Oracle上运行上述SQL查询时,我们将得到以下结果集:
| song |
|---------------------------------------------------|
| JP Cooper ft. Mali-Koa - All This Love |
| 2Pac ft. DMX - Rise Of A Champion (GalilHD Remix) |
| HAIM - Don't Save Me (Cyril Hahn Remix) |
| Ed Sheeran & Passenger - No Diggity (Kygo Remix) |
| Miyagi & Эндшпиль ft. Рем Дигга - I Got Love |
SELECT
CONCAT(CONCAT(artist, ' - '), title) AS song
FROM song
ORDER BY NEWID()
当在SQL Server上运行上述SQL查询时,我们将得到以下结果集:
| song |
|---------------------------------------------------|
| Miyagi & Эндшпиль ft. Рем Дигга - I Got Love |
| JP Cooper ft. Mali-Koa - All This Love |
| HAIM - Don't Save Me (Cyril Hahn Remix) |
| Ed Sheeran & Passenger - No Diggity (Kygo Remix) |
| 2Pac ft. DMX - Rise Of A Champion (GalilHD Remix) |
请注意,由于order by子句使用了NEWID函数调用,这些歌曲是按随机顺序列出的。
PostgreSQL
在PostgreSQL上,你需要使用random函数,如下例所示:
SELECT
artist||' - '||title AS song
FROM song
ORDER BY random()
当在PostgreSQL上运行上述SQL查询时,我们将得到以下结果集:
| song |
|---------------------------------------------------|
| 2Pac ft. DMX - Rise Of A Champion (GalilHD Remix) |
| JP Cooper ft. Mali-Koa - All This Love |
| Ed Sheeran & Passenger - No Diggity (Kygo Remix) |
| HAIM - Don't Save Me (Cyril Hahn Remix) |
| Miyagi & Эндшпиль ft. Рем Дигга - I Got Love |
请注意,由于order by子句使用了random函数调用,这些歌曲是按随机顺序列出的。
MySQL
在MySQL上,你需要使用RAND函数,如下面的例子所示:
SELECT
CONCAT(CONCAT(artist, ' - '), title) AS song
FROM song
ORDER BY RAND()
当在MySQL上运行前面提到的SQL查询时,我们将得到以下结果集:
| song |
|---------------------------------------------------|
| HAIM - Don't Save Me (Cyril Hahn Remix) |
| Ed Sheeran & Passenger - No Diggity (Kygo Remix) |
| Miyagi & Эндшпиль ft. Рем Дигга - I Got Love |
| 2Pac ft. DMX - Rise Of A Champion (GalilHD Remix) |
| JP Cooper ft. Mali-Koa - All This Love |