[英]MySQL / PHP joining single record to multiple records
我有一個名為ABC的表,其中包含3個字段:id1,id2,id3和data:
id1 | id2 | id3
________________
1 | 5 | 3
3 | 4 | 2
2 | 3 | 1
我有一個名為XYZ的第二張表,帶有2個字段,id和title以及data:
id | title
______________
1 | title_1
2 | title_2
3 | title_3
4 | title_4
5 | title_5
表ABC中的ID與表XYZ中每個記錄的ID相匹配。 id喜歡做的是將表ABC中的ID與表XYZ中的ID結合在一起,並在一行中顯示標題。 因此,如果輸出表ABC中的前兩個記錄,它將看起來像這樣:
title_1, title_5, title_3
title_3, title_4, title_2
用PHP輸出是可以的,我對SQL只是有點迷路。 我一直在嘗試使用左聯接,但距離還不很遠。 任何幫助將非常感激。
您可以使用不同的連接條件多次連接同一張表:
SELECT xyz1.title as title1, xyz2.title as title2, xyz3.title as title3
FROM ABC
JOIN XYZ as xyz1 ON xyz1.id = ABC.id1
JOIN XYZ as xyz2 ON xyz2.id = ABC.id2
JOIN XYZ as xyz2 ON xyz3.id = ABC.id3
這個應該正確輸出
title_1, title_5, title_3
title_3, title_4, title_2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.