问题
I have 2 tables :
albums (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.
Thanks you in advance :)
回答1:
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. 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)
回答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
Then you'll be able to access Author, Composer and Featured, plus all the album properties
回答3:
You just have to add the other fields to your query result too: 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 (e.g. a.*
).
来源:https://stackoverflow.com/questions/23425361/multiple-inner-join-erase-attributes