不同的顺序取决于条件

时间:2016-06-29 12:53:00

标签: mysql sql-order-by

我有一个'产品'有3列的表格:

id (int)
priority (1 or 0)
price (int)

在我按优先顺序订购产品后,我想按价格订购这两个子集。优先级= 1的子集按升序价格计算,优先级= 0的子集按降序价格计算。 我尝试过这样的事情:

SELECT * FROM product ORDER BY priority DESC, CASE priority = 1 THEN price END ASC, CASE priority = 0 THEN price END DESC

但我尝试的任何东西似乎都没有用。 有关如何处理此问题的任何想法? TIA

1 个答案:

答案 0 :(得分:2)

您的WHEN语法中缺少CASE。这有效:

SELECT * FROM product
ORDER BY priority DESC,
CASE WHEN priority = 1 THEN price END ASC,
CASE WHEN priority = 0 THEN price END DESC;

更简单的方法是运行两个查询,每个查询对应一个优先级,并使用UNION组合结果集:

SELECT * FROM product WHERE priority = 1 ORDER BY price ASC
UNION ALL
SELECT * FROM product WHERE priority = 0 ORDER BY price DESC