2015-11-05 50 views
1

在我的數據庫中,我有一個名爲posts的表和一個名爲topics的表。SQL JOIN爲每一行返回帶有錯誤ID的查詢

每個post有一個家長topic

在這種情況下posts.parent_topic是一個外鍵關聯topics.id

我attemping做一個JOIN讓我的查詢將從topics表返回正確的topics.topic_title。我已經能夠成功地做到這一點,但我注意到,我不再爲返回的任何東西獲得正確的posts.id

我的查詢:

$posts = $db->query(" 
    SELECT 
     * 
    FROM 
     posts 
    JOIN topics ON 
     posts.post_parent_topic = topics.id 
    ORDER BY 
     posts.created_on DESC 
    ")->fetchALL(PDO::FETCH_ASSOC); 

$posts可變我看到這些結果做了var_dump後:

array (size=2) 
    0 => 
    array (size=12) 
     'id' => string '1' (length=1) // this id is CORRECT for the post 
     'post_parent_topic' => string '1' (length=1) 
     'created_on' => string '2015-11-03 09:30:40' (length=19) 
     'post_title' => string 'Development Standards' (length=21) 
     'post_content' => string 'These are the development specifc standards.' (length=44) 
     'topic_title' => string 'Code Standards' (length=14) 
     'topic_content' => string 'These are the company programming standards.' (length=44) 
     'topic_parent_organization' => string '1' (length=1) 
    1 => 
    array (size=12) 
     'id' => string '1' (length=1) // this id is INCORRECT for the post, it should be an id of 2 (as it appears in the database) 
     'post_parent_topic' => string '1' (length=1) 
     'created_on' => string '2015-11-03 09:30:40' (length=19) 
     'post_title' => string 'Design Standards' (length=16) 
     'post_content' => string 'These are the design specific standards.' (length=40) 
     'topic_title' => string 'Code Standards' (length=14) 
     'topic_content' => string 'These are the company programming standards.' (length=44) 
     'topic_parent_organization' => string '1' (length=1) 

爲什麼每個帖子返回相同的id?我需要這篇文章的id,因爲它在我的數據庫中。

+0

有'ID ''帖子'表中的列? –

+1

你確定'id'來自'topics'而不是'posts'。通常最好先使用'AS'對每個表和字段進行別名,這樣您就可以看到哪個字段屬於每個表。 (即'SELECT p.id AS'posts_id',t.id AS'topics_id'FROM posts AS p LEFT JOIN topics AS t ON p.post_parent_topic = t.id ORDER BY p.created_on DESC') –

+0

@YeldarKurmangaliyev yes there是每個表中的id列。 – captainrad

回答

2

如果你有兩個poststopics表中id列,你可能需要給他們的別名,使其unambigious:

嘗試更改查詢到以下幾點:

SELECT p.*, t.id AS TopicId, t.topic_title, t.topic_content, t.topic_parent_organization 
FROM posts AS p 
JOIN topics AS t 
    ON posps.post_parent_topic = t.id 
ORDER BY p.created_on DESC