如何连接两次到另一张桌子?

时间:2013-09-10 12:55:35

标签: php mysql sql database

我收到了这段代码:

        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时,我收到一个错误。那是正确的方法呢?感谢。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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

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