SQL查询按组排序

时间:2011-05-12 06:23:21

标签: php mysql database

您好我需要查询帮助。这是我的查询&表结构。

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          | 
---------------------------------------------------

我希望它排序,以便它是alphabaticaly有序(product_name),同时保持底部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          | 
---------------------------------------------------

感谢任何帮助!

3 个答案:

答案 0 :(得分:2)

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 

答案 1 :(得分:0)

尝试

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 = 0) DESC, products_name LIMIT 10

目前我不确定您是否需要订购布尔表达式ASCDESC,所以请试试。

答案 2 :(得分:0)

如果您不限于10件商品,可以试试这个:

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