2016-11-23 58 views
0

不能在MySQL中也沒有PHP的專家,但是從下面的MySQL數據庫:獲取匹配對

ID Col_A Col_B Col_C 
id1 id2  id4  id3 
id2 id3  id1  id6 
id3 id8  id1  id5 
id4 id3  id7  id5 
id5 id9  id4  id1 

如何能夠找到匹配無論是在PHP或在MySQL使輸出將是對(在此示例):

id1-id2 
id1-id3 
id2-id1 
id3-id1 
id4-id5 
id5-id4 

結果顯示匹配的對。例如,對於行ID = id1,在Col_A中引用了id2,對於ID = id2,在Col_B中引用了id1,因此它們匹配:id1-id2和id2-id1。但是對於行ID = id1,在Col_B中引用了id4,如果我們查看行ID = id4,則在Col_A,Col_B和Col_C中沒有對id1的引用,因此沒有匹配。

我看了一下PHP中的array_intersect_key,但不知道如何處理這裏的多重遞歸,以及UNION在MySQL中,但不知道從哪裏開始。 與我在其他問題上看到的不同之處在於,在這裏,ID用於匹配。

我需要一點幫助,在此先感謝!

+1

我不要得到你的匹配對的定義...爲什麼'id1-id2'和'id1-id3'是匹配但id1-id4'不是? –

+0

你是如何形成配對並不完全清楚。你能添加一些解釋嗎? –

+0

是的,只是添加了一些解釋來解釋更多如何考慮比賽。 – hycday

回答

0

這是MySQL的痛苦,因爲它沒有CTE。開始是unpivoting數據

select id, col_a as id2 from t union all 
select id, col_b as id2 from t union all 
select id, col_c as id2 from t; 

然後這個地方,你簡單的希望對這個自聯接:

select t1.id, t1.id2 
from (select id, col_a as id2 from t union all 
     select id, col_b as id2 from t union all 
     select id, col_c as id2 from t 
    ) t1 join 
    (select id, col_a as id2 from t union all 
     select id, col_b as id2 from t union all 
     select id, col_c as id2 from t 
    ) t2 
    on t1.id = t2.id2 and t1.id2 = t2.id 
where t1.id < t1.id2; 

或者,你可以做到這一點使用exists

select t.id, t.id2 
from (select id, col_a as id2 from t union all 
     select id, col_b as id2 from t union all 
     select id, col_c as id2 from t 
    ) t 
where exists (select 1 from t t2 where t2.id = t.id2 and t2.col_a = t.id) or 
     exists (select 1 from t t2 where t2.id = t.id2 and t2.col_b = t.id) or 
     exists (select 1 from t t2 where t2.id = t.id2 and t2.col_c = t.id); 
+0

完美的作品。不顯示'重複',但它很好,我理解邏輯!謝謝 – hycday