2017-01-03 86 views
1

的兩列我有這個表:MySQL的排序一個表

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' 

謝謝!

+0

使用由Id命令。你想要嗎? –

+0

列在'id asc,for_id asc'中沒有排序,他不需要這個,他也沒有澄清這個問題。 – wajeeh

+0

你想要的真實順序是什麼? – wajeeh

回答

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 

and 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

+0

謝謝,但如果我向表中添加記錄,則查詢無法正常工作。 –

+0

[SQLFiddle](http://sqlfiddle.com/#!9/bf4c8/1) –

+0

@ChooHwan有關額外的記錄,您想要的結果是什麼? – Blank

1

只需使用order by,它可以通過獲得超過一場

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

如果你看問題中的sqlfiddle,你會看到你的答案是一樣的:) – wajeeh

0

使用秩序和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

+0

[鏈接](http://sqlfiddle.com/#!9/859933/23) –

+0

@ChooHwan你有答案您正在尋找?如果是這樣,你可以接受答案 –

+0

號請看看我的問題。 –