【问题标题】:mysql how to order by user defined order/sort by number of items on a fieldmysql如何按用户定义的顺序排序/按字段上的项目数排序
【发布时间】:2011-09-14 18:43:51
【问题描述】:

mysql如何按用户定义的顺序/排序进行排序

说一张桌子

---------+----------
name     | category
---------+----------
apple    | 0
orange   | 0
book     | 1
notebook | 1
textboo  | 1
phone    | 2

如何按以下类别排序,即类别=1,类别=0,类别=2 获得视图

---------+----------
name     | category
---------+----------
book     | 1
notebook | 1
textbook | 1
apple    | 0
orange   | 0
phone    | 2

我们如何为此编写一个 sql?

如果语句可以根据每个类别的项目数来识别和排序 desc ,那就更好了。

【问题讨论】:

    标签: mysql sql select sql-order-by


    【解决方案1】:

    你想这样做:

    SELECT Name, Category
    FROM MyTable
    ORDER BY 
        Case category
            when 1 then 1
            when 0 then 2
            else 3
        end,
        Name
    

    更新

    在第一个答案中,顺序是按类别固定的。当按类别中的项目数量排序时,您需要这样做:

    select name, Category, 
           (select count(*) from MyTable mt2 where mt2.Category = mt1.category) CatCount
    from MyTable mt1
    order by 3 DESC, name
    

    【讨论】:

    • 您可以将子查询作为一个表,因此它只会对表中找到的每一行运行一次(例如,请参阅我的答案)。
    【解决方案2】:

    如果要按类别中的条目数排序,可以这样做:

    SELECT my_table.name, my_table.category, cats.total FROM
        (SELECT category, COUNT(*) AS total FROM my_table GROUP BY category) cats
        INNER JOIN my_table ON my_table.category = cats.category
        ORDER BY cats.total DESC, my_table.name ASC
    

    【讨论】:

    • +1 因为这会随着每个类别中条目数量的变化而自我纠正
    【解决方案3】:

    如果您在编写查询时知道顺序,则可以使用 UNION ALL:

    SELECT name, category
    FROM table
    WHERE category = 1
    
    UNION ALL
    
    SELECT name, category
    FROM table
    WHERE category = 0
    
    UNION ALL
    
    SELECT name, category
    FROM table
    WHERE category = 2
    

    【讨论】:

    • UNION 不保证订单
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-02
    • 2012-11-08
    • 1970-01-01
    • 2014-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多