【问题标题】:referencing same row in multiple joins在多个连接中引用同一行
【发布时间】:2014-12-15 04:03:05
【问题描述】:

我有一个名为 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

提前致谢。

【问题讨论】:

  • 如果我正确理解了这个问题,那么您可能应该使用列别名。您正在使用两个表。他们看起来怎么样?另外,你不应该两次JOIN同一张桌子,你应该使用AND
  • 表 b 有 2 列:Contact 和 ContactB,它们都是与 relOwner 表的 OwnerID 列相关的整数。
  • 为什么不使用两个单独的查询,每个查询一个连接?

标签: php mysql join


【解决方案1】:

您似乎在表 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'];

【讨论】:

  • 还没有让它工作,但这对吗:ro1.RelationshipOwner as ro2RelationshipOwner?
  • 哎呀 - 很好发现。不应该是ro2.RelationshipOwner as ro2RelationshipOwner - 我已经修复了
猜你喜欢
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 2012-06-11
  • 1970-01-01
  • 1970-01-01
  • 2017-07-02
  • 2019-12-23
  • 2011-06-15
相关资源
最近更新 更多