gpt4 book ai didi

sql - "FROM a, b"和 "FROM a FULL OUTER JOIN b"有什么区别?

转载 作者:行者123 更新时间:2023-12-02 08:21:11 25 4
gpt4 key购买 nike

处理来自多个表的数据时,您可以通过多种不同的方式 JOIN这些表,每个表都会改变匹配列的处理方式。您也可以从多个表中提取数据,即 FROM [table a], [table b] .

这种方法似乎仍然以某种方式连接表格,如果我不得不猜测,我会说这种方法只是 FULL OUTER JOIN 的简写。 ,但我确定两者之间存在差异。

区别仅仅是FULL OUTER JOIN后续是 ON [table 1 specific column] = [table 2 specific column] ,还是有其他事情发生?

最佳答案

您的问题已得到解答,但从您的评论中我认为您是否完全理解问题仍然不确定。所以,我想我只需要添加另一个答案:-)

让我们从简单的开始

FROM a, b

这是一种过时的连接语法,在标准 SQL-1992 中被显式连接取代。有了上面的内容,您必须将连接条件(如果有)放在 WHERE 子句中。如果没有 WHERE 子句中的连接条件,这是一个交叉连接,您现在可以明确地将其写为
FROM a CROSS JOIN b

这告诉读者您有意想要 a 和 b 的所有组合(并且不仅忘记了连接条件或错误地删除了它)。一个例子是
FROM store CROSS JOIN product

在这里你把每家商店和每一种产品结合起来,不管商店是否真的有产品;您只需显示所有可能的组合。有两个商店和两个产品,结果可能如下所示:
store   products1      p1s1      p2s2      p1s2      p2

A CROSS JOIN is something rarely needed. In above case we might want to know all store product/combinations and select a 'yes' or 'no' for every line, so we see which products a store features and which not.

In a relational database we usually deal with table's relations, however, so let's add join criteria:

FROM a, b
WHERE a.col1 = b.col2

这是一个内部连接,我们只查找记录匹配。这现在写成
FROM a
INNER JOIN b ON a.col1 = b.col2

或(省略可选关键字 INNER ,因为默认情况下连接是内部连接):
FROM a
JOIN b ON a.col1 = b.col2

这是一个例子。我们有两个表格,其中包含每个部门和年度的费用和收入。
FROM dept_cost
JOIN dept_gain ON dept_gain.dept_no = dept_cost.dept_no AND dept_gain.year = dept.cost.year

假设表包含:
year   dept_no   total_cost2015   d001      200002016   d001      250002016   d002      10000

and

year   dept_no   total_gain2015   d001      400002015   d002      300002016   d001      50000

Then a result would be:

year   dept_no   total_cost   total_gain2015   d001      20000        400002016   d001      25000        50000

because only 2015/d001 and d001/2016 are found in both tables.

If you want to see the other data, too, you must outer join. You can outer join dept_gain to dept_cost, so as to see all costs - along with their gains if any. Or, vice versa, you outer join dept_cost to dept_gain, so as to see all gains - along with their costs if any. Or you full outer join, so as to see all data:

FROM dept_cost
FULL OUTER JOIN dept_gain ON dept_gain.dept_no = dept_cost.dept_no
AND dept_gain.year = dept.cost.year

year dept_no total_cost total_gain
2015 d001 20000 40000
2015 d002 30000
2016 d001 25000 50000
2016 d002 10000

CROSS JOIN 和FULL OUTER JOIN 都很少需要。因此,如果您还不了解它们,请不要担心。您通常只需要 INNER JOIN,有时需要 LEFT OUTER JOIN。

关于sql - "FROM a, b"和 "FROM a FULL OUTER JOIN b"有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36997207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com