php - 在多个连接中引用同一行

标签 php mysql join

我有一个名为 relOwner 的 mySQL 数据库,它有两列: 所有者 ID、关系所有者

我正在编写一个包含引用数据库的连接的查询:

$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

提前致谢。

最佳答案

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

关于php - 在多个连接中引用同一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27477168/

相关文章:

php - 单击行以使用其数据预填充表单仅显示第一条记录

mysql - sql使用内连接连接三个表

php - 获取html跨站,显示并获取元素值

mysql在插入多个之前触发

php - Laravel 5.2 - 过滤自定义属性然后分页

php - 从 mysql 回显 PHP 代码

sql - 删除连接的输出(记录在多个表中)

mysql - 如何从联接中的子查询访问父列

php:对于一个mysql表中的每条记录,显示第二个表中的所有记录

php - 在PHP中一行将关联数组转换为 "id = value, id = value"的字符串