admin管理员组文章数量:1406327
I want to sort products by newness first, i.e. date on which they were added but in stock products should come before out of stock products. I have a column of "stock" that tracks how many units I have in stock.
SELECT * FROM products ORDER BY stock DESC, date_added DESC
This simple query doesn't work because it will sort by stock first and if 2 products have same stock number, they'll be sorted by date. I need a way to convert stock into two numbers 1 (has stock) and 0 (no stock) and then sort them by date.
Can this be done?
I want to sort products by newness first, i.e. date on which they were added but in stock products should come before out of stock products. I have a column of "stock" that tracks how many units I have in stock.
SELECT * FROM products ORDER BY stock DESC, date_added DESC
This simple query doesn't work because it will sort by stock first and if 2 products have same stock number, they'll be sorted by date. I need a way to convert stock into two numbers 1 (has stock) and 0 (no stock) and then sort them by date.
Can this be done?
Share Improve this question asked Mar 6 at 5:28 WhipWhip 2,25426 silver badges50 bronze badges 2 |1 Answer
Reset to default 1You can do something like this:
SELECT *
FROM products
ORDER BY
CASE WHEN stock > 0 THEN 1 ELSE 0 END DESC,
date_added DESC;
CASE WHEN stock > 0 THEN 1 ELSE 0 END DESC
will make sure that all products that are in stock are ranked first (1 > 0)date_added DESC
will make sure that the newer ones will appear first
本文标签: Mariadb order by any positive number firstStack Overflow
版权声明:本文标题:Mariadb order by any positive number first - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744995470a2636644.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
ORDER BY stock='has stock' DESC, date_added DESC
– Akina Commented Mar 6 at 5:51