7

我有一张桌子“交易”

+---------+---------+
| deal_id | expired |
+---------+---------+
|       1 |       0 |
|       2 |       0 |
|       3 |       0 |
|       4 |       0 |
|       5 |       1 |
|       6 |       0 |
|       7 |       1 |
|       8 |       1 |
|       9 |       0 |
|      10 |       0 |
+---------+---------+

我想归档以下订单:

1) 底部的过期交易

2) deal_id 高于 5 在顶部的交易,按 deal_id 排序

3) 处理 id 低于/等于 5 在底部由 RAND 排序的种子


SELECT deal_id, expired FROM Deal ORDER by expired = 1, deal_id < 5, rand(1) desc

这个查询是错误的,因为表的顶部也将按 rand 排序,而我想按 deal_id desc 排序的顶部。


这是它应该照顾的方式:

+---------+---------+
| deal_id | expired |
+---------+---------+
|       10|       0 | top part ordered by
|       9 |       0 | deal_id desc 
|       6 |_______0 | if ( deal_id < 5 AND expired = 0 )
|       4 |       0 |  
|       1 |       0 | bottom part ordered
|       5 |       0 | by rand(seed) 
|       7 |       0 | expired = 1 at the bottom
|       5 |       1 |
|       7 |       1 |
|       8 |       1 |
+---------+---------+

是否可以通过仅使用“ORDER BY”中的表达式来存档?我知道我可以使用 UNION,但我真的不想,它会让我在我的框架中保持简单。

谢谢。

4

2 回答 2

13

像这样的东西?

SELECT
  deal_id,
  expired
FROM
  Deal
ORDER BY
  expired = 1,
  deal_id < 5,
  case when (expired=1 or deal_id<5)=false
       then deal_id
       else rand()
  end desc

在此处查看小提琴。

于 2013-03-06T18:26:56.667 回答
4

你可以使用 CASE 语句

ORDER BY CASE 
 WHEN expired = 1 THEN 99 
 WHEN deal_id < 5 THEN deal_id 
 WHEN deal_id > 5 THEN Rand() + 5 //so that the value is between 5 and 6
 ELSE 100 END
于 2013-03-06T18:23:52.983 回答