2015-11-05 78 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