我正在编写查询以显示数据并在该查询中添加 order by 子句。我的查询是
SELECT * FROM `coupons`
WHERE `status` = 'A' && `type` = '2'
&& `time` > CURDATE() && `start_date` <= CURDATE()
order by `stocks` asc
在上面的查询中,它按“股票”排序,但在某些情况下,股票为零,这种情况下我想在最后显示这一行。我该怎么办请帮忙。提前致谢。
order by CASE WHEN `stocks` = 0 THEN 1 ELSE 0 END asc , `stocks` asc
SELECT *, (if(`stocks` != 0,`stocks`,"")) as newstocks FROM `coupons`
WHERE `status` = 'A' && `type` = '2'
&& `time` > CURDATE() && `start_date` <= CURDATE()
order by newstocks asc
使用上面的代码。
默认情况下它是 asc 所以你不必提及它。试试下面的
SELECT * FROM coupons WHERE status = 'A' && type = '2' && time > CURDATE() && start_date <= CURDATE() order by case stock != 0 then stock end, stock
它将首先列出stocks 为nozero 的项目,然后列出stocks=zero 的行