MySQL - 订购查询并在顶部显示一个随机行

时间:2016-01-23 21:25:29

标签: mysql sql

我有一张表格如下:

ID  |  TICKET PRICE  |  VIP
----------------------------
 1  |     $45.00     |  1
 2  |     $40.00     |  1
 3  |     $20.00     |  0
 4  |     $65.00     |  0
 5  |     $45.00     |  1

我需要查询此表以按Price排序所有行,但始终显示一个随机行,其顶部有VIP = 1。例如,查询应返回:

ID  |  TICKET PRICE  |  VIP
----------------------------
2  |     $40.00     |  1 
3  |     $20.00     |  0    
1  |     $45.00     |  1
5  |     $45.00     |  1     
4  |     $65.00     |  0  

当您刷新页面时,行ID 5可能会成为第一行,因为它具有VIP = 1。

我目前的查询如下:

(SELECT * FROM tickets WHERE VIP=1 ORDER BY rand() LIMIT 1)
UNION
(SELECT * FROM tickets WHERE VIP=0 ORDER BY ticket_price ASC)

这个问题是它只会显示一个VIP行。我如何正确查询这些数据?

1 个答案:

答案 0 :(得分:2)

使用order by。这是一种方法:

select t.*
from (select t.*, (@rn := @rn + 1) as seqnum
      from tickets t cross join
           (select @rn := 0) params
      order by vip desc, rand()
     ) t
order by (seqnum = 1) desc, price asc;

这使用子查询来标识要保留在顶部的一行。然后它使用此信息在外部查询中进行排序。

如果您的行具有唯一标识符,您还可以执行以下操作:

select t.*
from tickets t cross join
     (select id from tickets where vip = 1 order by rand() limit 1) as t1
order by (t.id = t1.id) desc, price asc;