我有一张桌子,看起来像:
ID | TICKET PRICE | VIP ---------------------------- 1 | $45.00 | 1 2 | $40.00 | 1 3 | $20.00 | 0 4 | $65.00 | 0 5 | $45.00 | 1
我需要查询该表以按价格对所有行进行排序,但始终显示一个随机行,其顶部具有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行。我将如何正确查询这些数据?
使用order by。这是一种方法:
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;