简体   繁体   English

多个内部联接擦除属性

[英]Multiple Inner Join erase attributes

I have 2 tables : 我有2张桌子:

albums (idalbum, idauthor, idcompositor, idfeat) 相册(idalbum,idauthor,idcompositor,idfeat)

people (id, firstname, last name) 人(身份证,名字,姓氏)

My Query 我的查询

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

What i want : 我想要的是 :

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

My problem : 我的问题 :

When i print_r the Query i just have one first name and one last name, the "p2" values. 当我使用print_r查询时,我只有一个名字和一个姓氏,即“ p2”值。

Thanks you in advance :) 预先感谢您:)

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

Then you'll be able to access Author, Composer and Featured, plus all the album properties 然后,您将可以访问“作者”,“作曲家”和“精选”,以及所有专辑属性

Your problem is that each column has the same name. 您的问题是每个列都具有相同的名称。 When your result is converted to an PHP array the later columns overwrite the first column with the same index / column name. 当您的结果转换为PHP数组时,后面的列将使用相同的索引/列名称覆盖第一列。 You have to give each column a unique identifier, to access each single value. 您必须为每个列赋予唯一的标识符,以访问每个单个值。

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

As an alternative you can use another fetch style, which inserts the columns by its column number into the array. 作为替代方案,您可以使用另一种访存样式,该样式将按其列号插入列。 (If you are using PDO, see http://www.php.net/manual/en/pdostatement.fetch.php ) (如果您使用的是PDO,请参见http://www.php.net/manual/zh/pdostatement.fetch.php

You just have to add the other fields to your query result too: a.*,p.*,p1.*,p2.* 您也只需将其他字段添加到查询结果中: 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

With other databases (for example ORACLE) your original query would not even work because * in combination with several tables is not allowed without specifying which table the star belongs to (eg a.* ). 对于其他数据库(例如ORACLE),您的原始查询甚至无法使用,因为*如果没有指定星号属于哪个表(例如a.* ),则不允许*与多个表结合使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM