gpt4 book ai didi

php - SQL JOIN 返回每行 ID 错误的查询

转载 作者:行者123 更新时间:2023-11-29 05:15:26 26 4
gpt4 key购买 nike

在我的数据库中,我有一个名为 posts 的表和一个名为 topics 的表。

每个帖子都有一个父主题

在这种情况下,posts.parent_topic 是关联的 topics.id 的外键

我正在尝试执行 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,因为它在我的数据库中。

最佳答案

如果您在 poststopics 表中都有 id 列,您可能需要给它们别名以使其明确:

尝试将查询更改为以下内容:

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

关于php - SQL JOIN 返回每行 ID 错误的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33536608/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com