MySQL按一个表的两列排序

时间:2017-01-03 06:04:28

标签: mysql sorting

我有这张桌子:

CREATE TABLE table_name (id INT, for_id INT, comms VARCHAR(50));
    INSERT INTO table_name VALUES (1,0, 'boo'),
                                    (2,1, 'John'),
                                    (3,0, 'Zoe'),
                                    (4,3, 'bar'),
                                    (5,1, 'Don'),
                                    (6,3, 'FOO'),
                                    (7,1, 'Doe');

http://sqlfiddle.com/#!9/859933/6

我怎样才能获得下一个:

1.0.'boo'
2.1.'John'
5.1.'Don'
7.1.'Doe'
3.0.'Zoe'
4.3.'bar'
6.3.'FOO'

谢谢!

3 个答案:

答案 0 :(得分:2)

不确定这是否是您想要的,您应该对帖子中的结果顺序做一些解释。

select *
from table_name
order by 
    case when for_id = 0 then concat(id, for_id) + 0
         else concat(for_id, id) + 0
    end

SQLFiddle Demo Here

<强> 更新

再试一次,

select *
from table_name
order by 
    case when for_id = 0 then mod(concat(for_id, id) + 0, 10)
         else mod(concat(id, for_id) + 0, 10)
    end
    , id asc

SQLFiddle

再次更新:

select *
from table_name
order by 
    case when for_id = 0 then id
         else for_id
    end
    , id asc

SQLFiddle

答案 1 :(得分:1)

只需使用order by,就可以获得多个列

Select * from table_name 
  order by id asc, for_id asc;

答案 2 :(得分:0)

使用order by和Cancat

select Concat(id,'.',for_id) as id ,comms
from table_name
order by id asc,for_id asc

已更新:

根据您的情况使用order by并应用case语句

select *
from table_name
order by 
    case when for_id = 0 then concat(id, for_id) + 1
         else concat(for_id, id) + 0
    end

http://sqlfiddle.com/#!9/859933/25