MySQL:按多列排序结果

时间:2017-10-03 13:50:24

标签: mysql

假设我有下表“产品”:

+----+------------+------------+----------+------+
| ID | Name       | Purchased  | Promoted | Used |
+----+------------+------------+----------+------+
| 0  | TV         | 2017-10-02 | 0        | 0    |
| 1  | Radio      | 2017-08-27 | 1        | 0    |
| 2  | Fridge     | 2017-09-03 | 1        | 1    |
| 3  | Dishwasher | 2017-08-15 | 0        | 1    |
| 4  | Bike       | 2017-09-17 | 0        | 1    |
| 5  | Computer   | 2017-10-03 | 0        | 0    |
+----+------------+------------+----------+------+

现在我想按以下顺序获取所有记录:

  1. 按'已购买'

  2. 列排序的'已提升= 1'的行
  3. 按“已购买”

  4. 列排序的“已使用= 1”的行
  5. 按“已购买”列

  6. 排序的剩余行数

    结果:

    +---+------------+------------+---+---+
    | 2 | Fridge     | 2017-09-03 | 1 | 1 |
    +---+------------+------------+---+---+
    | 1 | Radio      | 2017-08-27 | 1 | 0 |
    | 4 | Bike       | 2017-09-17 | 0 | 1 |
    | 3 | Dishwasher | 2017-08-15 | 0 | 1 |
    | 5 | Computer   | 2017-10-03 | 0 | 0 |
    | 0 | TV         | 2017-10-02 | 0 | 0 |
    +---+------------+------------+---+---+
    

    MySQL查询是什么?

3 个答案:

答案 0 :(得分:0)

看起来很简单:

ORDER BY Promoted = 1 DESC,
         Used = 1 DESC,
         Purchased DESC

MySQL将布尔表达式评估为1和0。

答案 1 :(得分:0)

SELECT * FROM PRODUCTS ORDER BY PRODUCT.PROMOTED DESC, PRODUCT.USED DESC

答案 2 :(得分:-1)

您可以使用像

这样的UNION语句
SELECT * FROM products WHERE Promoted='1' ORDER BY Purchased 
UNION 
SELECT * FROM products WHERE Promoted!='1' AND Used='1' ORDER BY Purchased
UNION 
SELECT * FROM products WHERE Promoted!='1' AND Used!='1' ORDER BY Purchased