-1

我对 MySQL 很陌生,我正在尝试从 3 个表中进行选择。我不确定执行此操作的最佳方法,因此我尝试了以下查询(它一直有效,直到我将第二个内部联接添加到“主题”表中):

SELECT 
    posts.id AS post_id, 
    topic_id,
    date, 
    text, 
    username AS user,
    users.id AS user_id,
    topics.title AS title
FROM 
    posts 
INNER JOIN 
    users 
ON
    posts.user_id = users.id
INNER JOIN
    topics
ON
    topics.id =:topic_id
WHERE 
    topic_id =:topic_id
ORDER BY
    date ASC

那么有没有更简单的方法可以从 3 个表中进行选择?还是我做的很好,我只是在某个地方出错了?提前致谢

4

2 回答 2

0

您的第二个 JOIN 子句必须修复。我必须补充一点,如果您只打算使用主题表中的一行,则连接所有三个表可能不是最有效的方法。

SELECT 
    posts.id AS post_id, 
    topic_id,
    date, 
    text, 
    username AS user,
    users.id AS user_id,
    topics.title AS title
FROM 
    posts 
INNER JOIN 
    users 
ON
    posts.user_id = users.id
INNER JOIN
    topics
ON
    topics.id =posts.topic_id
WHERE 
    topics.id =:topic_id
ORDER BY
    date ASC
于 2013-10-26T10:03:19.310 回答
0

您不需要该WHERE子句。

而且我认为最后一个 ON 子句不应该:放在其 equal operator 上,而应该放在 equal operator 上=

它应该看起来像这样:

SELECT 
  posts.id AS post_id, 
  topic_id,
  date, 
  text, 
  username AS user,
  users.id AS user_id,
  topics.title AS title
FROM 
  posts 
INNER JOIN 
  users 
ON
  posts.user_id = users.id
INNER JOIN
  topics
ON
  topics.id = topic_id
ORDER BY
  date ASC
于 2013-10-26T10:04:03.423 回答