如果列具有由另一个值排序的特定值,如何将查询的行放到底部?

时间:2013-01-21 13:49:16

标签: mysql sql

我有一个包含3列的表产品:
- id_product
- quantity_in_stock
- product_name

如果它= 0,我希望将所有行ORDERED BY product_name和quantity_in_stock放在我的结果的底部。

我尝试过此查询,但不起作用:

(SELECT * 
FROM products 
WHERE quantity_in_stock != 0
ORDER BY product_name ASC)
UNION
(SELECT * 
FROM products 
WHERE quantity_in_stock = 0
ORDER BY product_name ASC)

也许有一种更简单的方法可以做到这一点,但这是星期一! ;)

1 个答案:

答案 0 :(得分:8)

ORDER BY可以包含任意表达式,因此您可以评估那些= 0并为它们分配更高值以便稍后排序的值:

SELECT * 
FROM products
ORDER BY 
  /* If quantity_in_stock is 0, assign a 1 otherwise 0. The ones sort after 0 */
  CASE WHEN quantity_in_stock = 0 THEN 1 ELSE 0 END ASC,
  /* Then sub-order by name */
  product_name ASC

由于MySQL的布尔评估返回1或0,您可以将其简化如下。但它不适用于每个RDBMS:

SELECT * 
FROM products
ORDER BY
  /* Will return 0 (false) for quantity_in_stock <> 0 and 1 if true */
  (quantity_in_stock = 0) ASC,
  product_name ASC

请注意,如果未将quantity_in_stock编入索引,则查询效果可能会受到负面影响。