不同的顺序取决于条件

Different order depending on condition

我有一个包含 3 列的 'product' table:

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

在我按优先级 desc 订购产品后,我想按价格订购两个子集。 priority = 1 的子集按价格递增,priority = 0 的子集按价格递减。 我试过这样的事情:

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

但我尝试的任何方法似乎都不起作用。 关于如何处理这个的任何想法? TIA

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

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