gpt4 book ai didi

php - SQL 查询按组排序

转载 作者:行者123 更新时间:2023-11-29 09:09:45 24 4
gpt4 key购买 nike

您好,我需要查询方面的帮助。这是我的查询和表结构。

SELECT *
FROM products_description a, products b
where a.products_id=b.products_id
AND b.products_status >0
AND a.products_name LIKE '%".$q."%'
ORDER BY b.products_quantity DESC LIMIT 10


---------------------------------------------------
| products_id | products_name | products_quantity |
---------------------------------------------------
| 980 | SOS | 21 |
---------------------------------------------------
| 101 | GOLD | 9 |
---------------------------------------------------
| 232 | BALL | 1 |
---------------------------------------------------
| 422 | SONG | O |
---------------------------------------------------
| 371 | ALL | O |
---------------------------------------------------
| 72 | FISH | O |
---------------------------------------------------

我希望它能够按字母顺序排序(产品名称),同时将数量为 0 的产品保留在底部。通常,我想要这样的结果:

---------------------------------------------------
| products_id | products_name | products_quantity |
---------------------------------------------------
| 980 | Ball | 1 |
---------------------------------------------------
| 101 | GOLD | 9 |
---------------------------------------------------
| 232 | SOS | 21 |
---------------------------------------------------
| 422 | All | O |
---------------------------------------------------
| 371 | FISH | O |
---------------------------------------------------
| 72 | SONG | O |
---------------------------------------------------

感谢任何帮助!

最佳答案

Select ...
From products_description a
Join products b
On a.products_id=b.products_id
Where b.products_status >0
And a.products_name LIKE '%".$q."%'
Order By Case When products_quantity = 0 Then 1 Else 0 End Asc
, a.products_name Asc
Limit 10

关于php - SQL 查询按组排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5974086/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com