在我的数据库中,我有一个名为posts
的表和一个名为topics
的表。
每个post
都有一个父topic
。
在这种情况下,posts.parent_topic
是关联的topics.id
我正在尝试执行JOIN
,以便我的查询将从topics.topic_title
表返回正确的topics
。我已经能够成功地做到这一点,但是我注意到我不再为返回的任何内容获得正确的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);
在var_dump
变量上执行$posts
后,我看到了以下结果:
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 :(得分:3)
如果您在id
和posts
表中都有topics
列,则可能需要为它们提供别名以使其明确无误:
尝试将查询更改为以下内容:
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