【问题标题】:Left join FROM multiple tables从多个表左连接
【发布时间】:2021-09-02 06:36:48
【问题描述】:

这个问题与我看到的已经回答的问题不同。是否可以使用多个“FROM”表进行左连接?当我尝试它(使用其他代码,但原理相同)时,我在'on子句'中收到错误'Unknown column'table1.otherId'。任何帮助将不胜感激。

类似这样的:

SELECT * 
FROM table1, table2
LEFT JOIN other_table
ON other_table.id = table2.id
AND other_table.otherId = table1.otherId

【问题讨论】:

  • 不要使用逗号连接语法,并且绝对不要将它与 ANSI JOIN 语法混合使用。
  • 样本数据、期望的结果以及对您想要完成的目标的清晰解释都会有所帮助。

标签: mysql sql database syntax left-join


【解决方案1】:

试试这样:-

SELECT * 
FROM table1
LEFT JOIN other_table
ON table1.id=other_table.id LEFT JOIN table2 ON
other_table.otherId = table2.id

【讨论】:

    【解决方案2】:

    答案是“不”

    但是你可以这样做:

    SELECT * FROM table2, other_table ON other_table.id = table2.id
    LEFT JOIN table1 ON other_table.otherId = table1.otherId
    
    

    【讨论】:

      【解决方案3】:

      这取决于你想做什么。您似乎想要前两个表的笛卡尔积,并在第三个表上查找:

      SELECT * 
      FROM table1 CROSS JOIN
           table2 LEFT JOIN
           other_table
           ON other_table.id = table2.id AND
              other_table.otherId = table1.otherId;
      

      逗号——应该从FROM 子句中永久禁止——类似于CROSS JOINs。但是,SQL 语句的解析是不同的。逗号防止它前面的表在它后面的ON 子句中使用;这就是你的错误的根源。

      【讨论】:

      • 在使用交叉连接之前要小心。交叉连接适用于创建两个数据集之间所有可能组合的目录。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-08
      • 1970-01-01
      • 2015-03-13
      • 1970-01-01
      • 1970-01-01
      • 2012-03-13
      • 1970-01-01
      相关资源
      最近更新 更多