【问题标题】:How to use multiple LEFT JOINs in SQL?如何在 SQL 中使用多个 LEFT JOIN?
【发布时间】:2011-06-24 10:21:57
【问题描述】:

sql查询中是否可以使用多个左连接?

    LEFT JOIN
        ab 
    ON
        ab.sht = cd.sht

我想添加一个这样的查询吗? 会有用吗?

    LEFT JOIN
        ab AND aa
    ON
        ab.sht = cd.sht
           AND
        aa.sht = cc.sht

这行得通吗?

【问题讨论】:

    标签: sql join left-join


    【解决方案1】:

    是的,这是可能的。每个连接表都需要一个 ON。

    LEFT JOIN ab
      ON ab.sht = cd.sht
    LEFT JOIN aa
      ON aa.sht = cd.sht
    

    顺便说一下,http://bentilly.blogspot.com/2011/02/sql-formatting-style.html 中描述了我对复杂 SQL 的个人格式偏好。如果你要写很多这样的东西,它可能会有所帮助。

    【讨论】:

      【解决方案2】:

      是的,但是语法和你的不一样

      SELECT
          <fields>
      FROM
          <table1>
          LEFT JOIN <table2>
              ON <criteria for join>
              AND <other criteria for join>
          LEFT JOIN <table3> 
              ON <criteria for join>
              AND <other criteria for join>
      

      【讨论】:

      • 感谢您在 JOIN 上显示 AND 标准。我将一些搜索词错误地移动到 WHERE 子句中,这让我大吃一惊!
      • 应该选择最佳答案。
      【解决方案3】:

      所需的 SQL 将类似于:-

      SELECT * FROM cd
      LEFT JOIN ab ON ab.sht = cd.sht
      LEFT JOIN aa ON aa.sht = cd.sht
      ....
      

      希望对你有帮助。

      【讨论】:

      • 以这种格式查看 LEFT JOIN 的,一个接一个真的是看透了。
      【解决方案4】:

      您有两种选择,具体取决于您的餐桌顺序

      create table aa (sht int)
      create table cc (sht int)
      create table cd (sht int)
      create table ab (sht int)
      
      -- type 1    
      select * from cd
      inner join cc on cd.sht = cc.sht
      LEFT JOIN ab ON ab.sht = cd.sht
      LEFT JOIN aa ON aa.sht = cc.sht
      
      -- type 2
      select * from cc
      inner join cc on cd.sht = cc.sht
      LEFT JOIN ab
      LEFT JOIN aa
      ON aa.sht = ab.sht
      ON ab.sht = cd.sht
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-30
        • 2010-10-01
        • 2010-09-29
        • 1970-01-01
        相关资源
        最近更新 更多