多个内部联接擦除属性

时间:2014-05-02 09:56:24

标签: php mysql sql inner-join

我有两张桌子:

专辑(idalbum,idauthor,idcompositor,idfeat)

人(id,名字,姓氏)

我的查询

SELECT * FROM albums  a
INNER JOIN people p ON a.idauthor = p.id
INNER JOIN people p1 ON a.idcompositor = p1.id
INNER JOIN people p2 ON a.idfeat = p2.id
where a.idalbum=:id

我想要的是什么:

Album,
p[First Name, Last Name],
p1[First Name, Last Name],
p2[First Name, Last Name]

我的问题:

当我打印__查询时,我只有一个名字和一个姓氏,“p2”值。

提前感谢您:)

3 个答案:

答案 0 :(得分:2)

SELECT a.*, 
   CONCAT(p.firstname, ' ', p.lastname) AS Author,  
   CONCAT(p1.firstname, ' ', p1.lastname) AS Composer, 
   CONCAT(p2.firstname, ' ', p2.lastname) AS Featured FROM albums a
INNER JOIN people p ON a.idauthor = p.id
INNER JOIN people p1 ON a.idcompositor = p1.id
INNER JOIN people p2 ON a.idfeat = p2.id
where a.idalbum=:id

然后,您将能够访问“作者”,“作曲家”和“精选”以及所有专辑属性

答案 1 :(得分:1)

您的问题是每列的名称相同。将结果转换为PHP数组时,后面的列将使用相同的索引/列名覆盖第一列。您必须为每列提供唯一标识符,以访问每个单独的值。

SELECT *, p.firstname as p_firstname, p.lastname AS p_lastname,
p1.first_name AS p1_firstname, [...]
FROM albums  a
INNER JOIN people p ON a.idauthor = p.id
INNER JOIN people p1 ON a.idcompositor = p1.id
INNER JOIN people p2 ON a.idfeat = p2.id
where a.idalbum=:id

作为替代方法,您可以使用另一种获取样式,该样式将列的列号插入到数组中。 (如果您使用的是PDO,请参阅http://www.php.net/manual/en/pdostatement.fetch.php

答案 2 :(得分:0)

您只需将其他字段添加到查询结果中: a.*,p.*,p1.*,p2.*

SELECT a.*,p.*,p1.*,p2.* FROM albums  a
INNER JOIN people p ON a.idauthor = p.id
INNER JOIN people p1 ON a.idcompositor = p1.id
INNER JOIN people p2 ON a.idfeat = p2.id
where a.idalbum=:id

对于其他数据库(例如ORACLE),原始查询甚至不起作用,因为*与多个表组合在一起而不指定该星所属的表(例如a.*)。< / p>