2017-07-25 11 views
1

我表演上的不同TYPE_ID同一個表t(TYPE_ID,PLACE_NAME)聯接:MySQL的:在同一臺加入與排序

------------------ 
type_id|place_name 
-------|---------- 
    1 | A 
    1 | B 
    2 | X 
    2 | Y 
------------------ 

我的查詢是:

select t1.type_id, t1.place_name 
from t as t1 
join t as t2 
on 
    t1.type_id!= t2.type_id AND 
    t1.place_name!=t2.place_name; 

我得到結果:

------------------- 
type_id|place_name 
-------|----------- 
    2 | X 
    2 | Y 
    2 | X 
    2 | Y 
    1 | A 
    1 | B 
    1 | A 
    1 | B 
------------------- 

但我想導致這樣的:

------------------- 
type_id|place_name 
-------|----------- 
    1 | A 
    2 | X 
    1 | A 
    2 | Y 
    1 | B 
    2 | X 
    1 | B 
    2 | Y 
------------------- 

我需要使用order by排序結果。請幫忙。

+0

感謝編輯bro @AlexTartan – BibanCS

+1

您使用什麼邏輯來排列行? – Eric

+0

'...按地點名稱排序,type_id' –

回答

0

如果你想要怎樣的一個壓縮秩序的,也可能是這樣的:

select t1.type_id, t1.place_name 
from t as t1 
join t as t2 
on 
    t1.type_id!= t2.type_id AND 
    t1.place_name!=t2.place_name 
order by 
    least(t1.place_name, t2.place_name), 
    greatest(t1.place_name, t2.place_name), 
    t1.type_id 

SQLFiddle

既然你無法解釋的順序完全邏輯,我不能告訴你是否適合其他數據。您可能需要使用兩列的組合,而不是place_name

+0

感謝bro @PaulSpiegel。有用。 – BibanCS