【问题标题】:What is the difference between writing sql join on together and separately?一起编写sql join和单独编写sql join有什么区别?
【发布时间】:2020-11-20 05:09:39
【问题描述】:

我的问题是两者有什么区别

SELECT id, name
FROM table_a a
JOIN table_b b
LEFT JOIN table_c c
ON a.id = b.id and a.name = c.name

SELECT id, name
FROM table_a a join table_b b on a.id=b.id
left join table_c on a.name = c.name

【问题讨论】:

  • 第一个版本真的运行了吗?如果是,结果集是否相同?
  • 您能否分享您自己用于此测试的数据以及您亲眼看到的输出?
  • 我认为第一个查询实际上不会起作用。 Join 没有 onusing 将返回语法错误。
  • 查询在 MySQL 中是合法的(除了一个错字 - 在第二个查询中 table_c 的别名丢失)。
  • @t.peter 没有 ON 或 USING 的 JOIN 就可以了

标签: mysql sql join left-join inner-join


【解决方案1】:
CREATE TABLE table_a (id INT, name INT) 
SELECT 1 id, 1 name UNION SELECT 2,2 UNION SELECT 4,4;
CREATE TABLE table_b (id INT) 
SELECT 1 id UNION SELECT 2 UNION SELECT 3;
CREATE TABLE table_c (name INT) 
SELECT 1 name UNION SELECT 3 UNION SELECT 4;
SELECT *
FROM table_a a
JOIN table_b b
LEFT JOIN table_c c
ON a.id = b.id and a.name = c.name
a.id | a.name | b.id | c.name -: | ---: | -: | ---: 4 | 4 | 1 | 2 | 2 | 1 | 1 | 1 | 1 | 1 4 | 4 | 2 | 2 | 2 | 2 | 1 | 1 | 2 | 4 | 4 | 3 | 2 | 2 | 3 | 1 | 1 | 3 |

生成前两个表的行中的所有对(不带 ON 的 JOIN 充当 CROSS JOIN),然后仅将第三个表连接到匹配的对。

SELECT *
FROM table_a a join table_b b on a.id=b.id
left join table_c c on a.name = c.name
a.id | a.name | b.id | c.name -: | ---: | -: | ---: 1 | 1 | 1 | 1 2 | 2 | 2 |

仅生成前两个表的行中的匹配对,然后将第三个表连接到匹配对。

db小提琴here

【讨论】:

    猜你喜欢
    • 2010-09-24
    • 2011-03-14
    • 2014-02-07
    • 1970-01-01
    • 2010-09-07
    • 1970-01-01
    • 2016-08-23
    相关资源
    最近更新 更多