SQL JOIN returns 每行 ID 错误的查询

SQL JOIN returns query with wrong ids for each row

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

的 table

每个 post 都有一个父 topic

在这种情况下 posts.parent_topic 是关联 topics.id

的外键

我正在尝试执行 JOIN,以便我的查询 return 来自 topics table 的正确 topics.topic_title。我已经能够成功地做到这一点,但是我注意到我不再为 returned.

的任何内容获得正确的 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)

为什么每个 post return 都是一样的 id?我需要 post 的 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