在多个连接中引用相同的行

时间:2014-12-15 04:03:06

标签: php mysql join

我有一个名为relOwner的mySQL数据库,它有两列: OwnerID,RelationshipOwner

我正在编写一个带有引用db:

的连接的查询
$query = "SELECT b.Contact, b.ContactB, relOwner.OwnerID, relOwner.RelationshipOwner 
    FROM b 
    Left JOIN relOwner
    ON b.Contact = relOwner.OwnerID
    Left JOIN relOwner
    ON b.ContactB = relOwner.OwnerID
";

如何在我的php中单独引用RelationshipOwner的值?

$RelationshipOwner = $row['RelationshipOwner'];
$RelationshipOwnerB = $row['RelationshipOwner']; <--- Get value from second JOIN

提前致谢。

1 个答案:

答案 0 :(得分:3)

您似乎在表b上有两个外键列到表relOwner(即ContactContactB)。

根据Sverri的评论,您需要为表使用不同的别名(我使用过ro1ro2),并从不同的表列中设置不同的名称(例如前缀带有ro2)的第二个表格列:

SELECT b.Contact, b.ContactB, ro1.OwnerID, ro1.RelationshipOwner, 
   ro2.OwnerID as ro2OwnerId, ro2.RelationshipOwner as ro2RelationshipOwner
FROM b -- Is this table Contact? If so then "Contact b"
  Left JOIN relOwner ro1
  ON b.Contact = ro1.OwnerID
  Left JOIN relOwner ro2
  ON b.ContactB = ro2.OwnerID;

然后您可以参考:

$row['ro2RelationshipOwner'];