按城市定义自定义订单

时间:2015-04-23 09:44:48

标签: php mysql

我试图定义一个自定义的ORDERY BY城市。

这样的事情:

New York (255)
Paris (26)
Vien(15)

然后ORDER BY city ASC

我已经尝试过此查询,但它无法正常工作:

SELECT count(id_item) as q, city FROM item GROUP BY city ORDER BY FIELD(city,'New York','Paris','Vien'), city ASC

3 个答案:

答案 0 :(得分:4)

你可以这样做:

SELECT 
    count(id_item) as q, 
    city 
FROM 
    item 
GROUP BY 
    city 
ORDER BY
    ( 
        CASE 
            WHEN city='New York' THEN 1
            WHEN city='Paris' THEN 2
            WHEN city='Vien' THEN 3
            ELSE 4
        END
    ) ASC,
    city ASC

答案 1 :(得分:1)

ORDER BY关键字默认按升序对记录进行排序。要按降序对记录进行排序,可以使用DESC关键字。试试这个 -

SELECT count(id_item) as q, city FROM item GROUP BY city ORDER BY city;

对于下降,你可以做这样的事情 -

SELECT count(id_item) as q, city FROM item GROUP BY city ORDER BY city DESC;

要使用自己的首选顺序获取行,SELECT查询将如下所示:

SELECT 
    count(id_item) as q, 
    city 
FROM 
    item 
GROUP BY 
    city 
ORDER BY
    ( 
        CASE 
            WHEN city='New York' THEN 1
            WHEN city='Paris' THEN 2
            WHEN city='Vien' THEN 3
            ELSE 4
        END
    ) ASC,
    city ASC

答案 2 :(得分:0)

你可以order by city='New York' desc, city='Paris' desc, city='Vien' desc, city

甚至order by city in ('New York', 'Paris', 'Vien') desc, city因为这3个已经按字母顺序排列