MySQL加入3个级联表

时间:2017-01-09 15:59:33

标签: php mysql select join inner-join

我已经看到很多例子可以将多个表连接回一个主表,但是这个查询的不同之处在于它的级联。

我有3个类似于下面的表格(简化为了简化):

**CONTACTS**     
--------------------------------------------
Cid    name
--------------------------------------------
1      John
2      Peter
3      Karl


**OPPORTUNITIES**
--------------------------------------------
Oid   Cidlink   title
--------------------------------------------
1     2         php lookup script
2     2         php facial recognition
3     3         html email template
4     1         javascript verification

**ATTACHMENTS**
--------------------------------------------
Aid    Oidlink  attachment
--------------------------------------------
1     3         received enquiry
2     3         header and footer done
3     3         pixel trace image done on server
4     2         database structure done      
5     2         html get form done

如您所见,附件链接回与联系人相关的机会和机会。除了通过商机表,附件不会直接链接到联系人。

我需要创建一个记录集,包括来自所有3个表的字段,并且正在努力。

SELECT CONTACTS.*, OPPORTUNITIES.*, ATTACHMENTS.*
FROM ATTACHMENTS
    INNER JOIN OPPORTUNITIES
        ON CONTACTS.Cid = OPPORTUNITIES.Cidlink
    INNER JOIN ATTACHMENTS
        ON OPPORTUNITIES.Oid = ATTACHMENTS.Oidlink

ORDER BY ****whatever****

我是否接近或者我是以错误的方式接近这个?

1 个答案:

答案 0 :(得分:0)

我认为你的意思是让联系人成为第一张没有附件的表...

SELECT CONTACTS.*, OPPORTUNITIES.*, ATTACHMENTS.*
FROM ATTACHMENTS  --- This is wrong
INNER JOIN OPPORTUNITIES
  ON CONTACTS.Cid = OPPORTUNITIES.Cidlink
INNER JOIN ATTACHMENTS
  ON OPPORTUNITIES.Oid = ATTACHMENTS.Oidlink
ORDER BY ****whatever****

我认为你的意思是(从长远来看,使用别名更容易阅读)

SELECT C.*, O.*, A.*
FROM Contacts C
INNER JOIN OPPORTUNITIES O
   ON C.Cid = O.Cidlink
INNER JOIN ATTACHMENTS A
   ON O.Oid = A.Oidlink
ORDER BY ****whatever****

既然你表示你需要所有3个表中的字段,我假设INNER JOIN在这里是合适的;但也许你想使用OUTER JOIN来包含所有联系人? 包括所有联系人及其存在的机会。 并包括机会的所有附件(如果存在)

SELECT C.*, O.*, A.*
FROM Contacts C
LEFT JOIN OPPORTUNITIES O
   ON C.Cid = O.Cidlink
LEFT JOIN ATTACHMENTS A
   ON O.Oid = A.Oidlink
ORDER BY ****whatever****

为了更好地理解联接,来自CodingHorror的这种Venn Diagram方法是一个良好的开端。