MySQL ORDER BY two fields condition

陌路散爱 提交于 2019-12-12 02:27:29

问题


I have a problem with creating select query ordered by following logic:

SELECT * FROM Products WHERE 1 ORDER BY Stock > 0, Price DESC

Table sample:

+---------+-------+-------+
| Product | Price | Stock |
+---------+-------+-------+
| Car     |  3500 |    30 |
| Boat    |  7500 |     6 |
| Bike    |   150 |   220 |
| Plane   | 55000 |     0 |
+---------+-------+-------+

The desired result is, that the table will be ordered by price if the stock value is greater than 0.

So the result should be:

+---------+-------+-------+
| Product | Price | Stock |
+---------+-------+-------+
| Boat    |  7500 |     6 |
| Car     |  3500 |    30 |
| Bike    |   150 |   220 |
| Plane   | 55000 |     0 |
+---------+-------+-------+

Any ideas?


回答1:


The result of a comparison in MySQL is 0 or 1. So Stock > 0 is 1 if true. And 1 and greather than 0. So either use

ORDER BY Stock = 0 ASC, Price DESC

or

ORDER BY Stock > 0 DESC, Price DESC

or

ORDER BY case when Stock > 0
              then 1
              else 2
         end, 
         Price DESC


来源:https://stackoverflow.com/questions/32742718/mysql-order-by-two-fields-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!