2

我得到了这个代码:

        SELECT
            topics.id,
            topics.id_first,
                            posts.id_first
          FROM topics
        LEFT
          JOIN posts
            ON posts.id = topics.id_first_msg

我的意图是做这样的事情:

        SELECT
            topics.id,
            topics.id_first,
                            posts.id_first,
                            posts.id_last
          FROM topics
        LEFT
          JOIN posts
            ON posts.id = topics.id_first_msg
        LEFT
          JOIN posts
            ON posts.id = topics.id_last_msg

但是,当我尝试两次 Left Join 时,我得到一个错误。那么哪个是正确的方法呢?谢谢。

4

3 回答 3

4

您需要为多次加入的表提供别名:

SELECT
    topics.id,
    topics.id_first,
    p1.id_first,
    p2.id_last
FROM topics
LEFT JOIN posts p1 ON p1.id = topics.id_first_msg
LEFT JOIN posts p2 ON p2.id = topics.id_last_msg
于 2013-09-10T12:57:45.467 回答
1

您必须为第二个左连接起别名;

    SELECT
        topics.id,
        topics.id_first,
                        posts.id_first,
                        posts2.id_last
      FROM topics
    LEFT
      JOIN posts
        ON posts.id = topics.id_first_msg
    LEFT
      JOIN posts AS posts2
        ON posts2.id = topics.id_last_msg
于 2013-09-10T12:57:47.660 回答
0

帖子表不明确。首先 - 你真的需要加入两次吗?你不能这样做:

    SELECT
        topics.id,
        topics.id_first,
        posts.id_first,
        posts.id_last,
        posts.id_first,
        posts.id_last
      FROM topics
    LEFT
      JOIN posts
        ON posts.id = topics.id_first_msg

第二 - 如果你真的必须加入两次 - 给帖子表两个不同的别名(你仍然需要编辑选定的列)

于 2013-09-10T12:58:40.987 回答