我有一个包含两个字段的表,它引用了另一个表的ID。我需要从两个字段的另一个表中提取名称。
例如
Table1 worker1 = 2 (2 is key to other table) worker2 = 4Table2 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字段的方法吗?
答案 0 :(得分:16)
您应该将字段别名如下:
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 ...
答案 1 :(得分:-1)
SELECT xxx, p1.NAME AS p1Name, p2.NAME AS p2Name FROM Table1
$worker1name = $rec['p1Name'];
$worker2name = $rec['p2Name'];