在mysql

时间:2016-11-10 15:43:41

标签: mysql

我有这样的查询。

select * from test order by rank

enter image description here

此查询按排名显示记录顺序。现在,我的排名列范围从1到500000.我想查询显示记录,排名列中最多100000他们显示为旧查询然后100000到400000 他们应该随机显示然后旧查询400000到500000。我试过这个。

(SELECT * FROM `test` WHERE `rank` <= 100000 ORDER BY `rank`)
UNION
(SELECT * FROM `test` WHERE `rank` > 100000 AND `rank` <= 400000 ORDER BY RAND())
UNION
(SELECT * FROM `test` WHERE `rank` > 400000 ORDER BY `rank`)

但它总是显示如下我希望它在排名栏100000到400000之间重新输入。

enter image description here

1 个答案:

答案 0 :(得分:0)

因此,您需要编写两个SELECT语句,由UNION组合:

-- Display ordered way till 100000
SELECT * FROM `test` WHERE `rank` <= 100000 ORDER BY `rank`
--- Join it.
UNION
-- Display random way after 400000
SELECT * FROM `test` WHERE `rank` > 100000 AND `rank` <= 400000 ORDER BY RAND()
-- Join it.
UNION
-- Display ordered way till 400000
SELECT * FROM `test` WHERE `rank` > 400000 ORDER BY `rank`

最终,这将显示所有记录,唯一的事情是,第一个400000记录按升序显示,而下一个记录是随机的。

小提琴:http://sqlfiddle.com/#!9/7521d/2