【问题标题】:mysql join aliases same tablemysql连接别名同一张表
【发布时间】:2013-06-08 13:34:01
【问题描述】:

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

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: How to associate a column alias with a specific JOIN clause

【问题讨论】:

    标签: mysql sql join


    【解决方案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
    

    【讨论】:

    • 非常感谢chue x,这非常有效。事实上,只有 contact_id 不正确。