php – Mysql多个左连接在同一个表上

前端之家收集整理的这篇文章主要介绍了php – Mysql多个左连接在同一个表上前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个表有两个字段,引用另一个表的ID.我需要从两个字段的另一个表中提取名称.

例如.

 
Table1
worker1 = 2  (2 is key to other table)
worker2 = 4

Table2 ID NAME 1 Bill 2 Fred 3 John 4 Paul

我需要获得$worker1name = Fred和$worker2name = Paul.

所以我会说:

SELECT xxx,NAME?,NAME? FROM Table1
LEFT JOIN Table2 AS p1 ON Table1.worker1 = Table2.ID
LEFT JOIN Table2 AS p2 ON Table1.worker2 = Table2.ID
WHERE ...

$table = MysqL_query(...);
$rec = MysqL_fetch_assoc($table);
$worker1name = $rec['???'];
$worker2name = $rec['???'];

我在最后两个语句中插入什么来获取这两个名称.或者更准确地说,我必须添加到SELECT中以指定我想要从表2中调用两个不同版本的NAME字段吗?

您应该将字段别名如下:
SELECT
   xxx,p1.NAME as p1name,p2.NAME as p2name
FROM Table1
LEFT JOIN Table2 AS p1 ON Table1.worker1 = p1.ID
LEFT JOIN Table2 AS p2 ON Table1.worker2 = p2.ID
WHERE ...

猜你在找的PHP相关文章