MySQL发布连接表,其中两列相对于一列

时间:2016-10-21 17:51:33

标签: php mysql join

我有一个带有id,first,last和identification列的联系人表。试图让名称显示在更大的连接中。加入两个列时,我无法显示它。

表:

检查  ID  ORDER_ID  Inspector_Id

联系人  ID  名字  姓  订货人  检查员

这是我的选择:

$sql = " SELECT 
        Inspections.Id,     
        Inspections.Orderer_Id,
        Inspections.Inspector_Id,   
        Contacts.Id 
        Contacts.First_Name AS OFirst,
        Contacts.Last_Name AS OLast,
        Contacts.First_Name AS IFirst,
        Contacts.Last_Name AS ILast,

FROM Inspections
JOIN Contacts ON Inspections.Orderer_Id &&         Inspections.Inspector_Id=Contacts.Id
WHERE
                Inspections.Id = " . $trigger . ";";

这只是最新的尝试。我已经尝试了很多方法来加入它们,但我想我只是很难翻译我在搜索时找到的代码。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

如果Inspector和Orderer是同一个人,那么您当前的查询只会起作用(一旦清除语法错误),如果不是,您必须使用表别名连接两次联系人:

 SELECT 
        Inspections.Id,     
        Inspections.Orderer_Id,
        Inspections.Inspector_Id,   
        orderer.Id AS OId,
        orderer.First_Name AS OFirst,
        orderer.Last_Name AS OLast,
        inspector.Id AS IId,
        inspector.First_Name AS IFirst,
        inspector.Last_Name AS ILast    
FROM Inspections
JOIN Contacts AS orderer ON Inspections.Orderer_Id = orderer.Id
JOIN Contacts AS inspector ON Inspections.Inspector_Id = inspector.Id
WHERE Inspections.Id = xxxx