簡體   English   中英

多個內部聯接擦除屬性

[英]Multiple Inner Join erase attributes

我有2張桌子:

相冊(idalbum,idauthor,idcompositor,idfeat)

人(身份證,名字,姓氏)

我的查詢

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]

我的問題 :

當我使用print_r查詢時,我只有一個名字和一個姓氏,即“ p2”值。

預先感謝您:)

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

然后,您將可以訪問“作者”,“作曲家”和“精選”,以及所有專輯屬性

您的問題是每個列都具有相同的名稱。 當您的結果轉換為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/zh/pdostatement.fetch.php

您也只需將其他字段添加到查詢結果中: 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.* ),則不允許*與多個表結合使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM