1

我有一个带有录音的音乐目录。每个录音都有一个所有者和作者。这些表是:

recordings
recordings_authors(Fk rec_id, Fk contact_id)
recordings_owners(Fk rec_id, Fk contact_id)
contacts (name of people)

最后的回声将显示:

Title: (name of title)
Author: (name from contacts)
Owner: (name from contacts)

以下工作正常,除了所有者显示为与作者相同的联系人。完全删除 JOIN 作者仍然会引发错误。

SELECT recordings.title,contactsauthors.name AS authorname,contactsowners.name AS ownername
FROM recordings

JOIN recordings_authors AS authors ON recordings.id=authors.rec_id
JOIN contacts AS contactsauthors ON authors.rec_id=contactsauthors.id

JOIN recordings_owners AS owners ON recordings.id=owners.rec_id 
JOIN contacts AS contactsowners ON owners.rec_id=contactsowners.id

WHERE recordings.id=1


$row=mysqli_fetch_assoc($results);
echo $row['title'].'<h2>Credits</h2>Author: '.$row['authorname'].'<br>Owner: '.$row['ownername'];

我可以在这里找到的最佳答案是这个 MySQL:如何将列别名与特定的 JOIN 子句相关联

4

1 回答 1

1

您在联系人联接中使用了错误的键。您应该使用contact_id而不是rec_id

SELECT recordings.title,contactsauthors.name AS authorname,contactsowners.name AS ownername

FROM recordings

JOIN recordings_authors AS authors ON recordings.id=authors.rec_id 
JOIN contacts AS contactsauthors ON authors.contact_id=contactsauthors.id
-- here ----------------------------------> ^^^^^^^^^^

JOIN recordings_owners AS owners ON recordings.id=owners.rec_id 
JOIN contacts AS contactsowners ON owners.contact_id=contactsowners.id
-- here --------------------------------> ^^^^^^^^^^

WHERE recordings.id=1
于 2013-06-08T13:53:53.993 回答