mysql条件排序_MySql条件排序

bd96500e110b49cbb3cd949968f18be7.png

I have this table (simplified):

CREATE TABLE `my_table` (

`id` INT NOT NULL AUTO_INCREMENT ,

`item_name` VARCHAR(45) NULL ,

`price` DECIMAL(10,0) NULL ,

PRIMARY KEY (`id`) )

I need to select all items from the table, ordered this way:

1. items with price > 0.00 first, ordered by price ASC

2. items with price = 0.00 last, ordered by id

I tried this:

SELECT *

FROM my_table

WHERE 1

ORDER BY

CASE price WHEN !0.00 THEN price

ELSE id

END

ASC

And i get results like

item_name | price

----------|-------

foo | 150,00

bar | 0,00

baz | 500,00

hum | 0,00

How do I build the query to have

item_name | price

----------|-------

foo | 150,00

baz | 500,00

bar | 0,00

hum | 0,00

?

Thank you for your time

解决方案

This will do the trick..

SELECT *

FROM my_table

WHERE 1

ORDER BY

CASE price WHEN 0 THEN 1

ELSE -1

END ASC, price asc, id asc

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值