Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 自然全外接?_Sql_Sql Server_Join - Fatal编程技术网

Sql 自然全外接?

Sql 自然全外接?,sql,sql-server,join,Sql,Sql Server,Join,有三种关系(t1、t2、t3): 查询是: select * from t1 natural full outer join (t2 natural full outer join t3); select*from t2 natural full outer join t3的结果是: ----------------- a | b | c | 2 | 3 4 | | 5 ------------------ 然后我试着: select*从t1自然

有三种关系(t1、t2、t3):

查询是:

select * from t1 natural full outer join (t2 natural full outer join t3); 
select*from t2 natural full outer join t3
的结果是:

-----------------
  a  |  b  |  c

     | 2   | 3

  4  |     | 5
------------------
然后我试着:

select*从t1自然完全外部连接(结果)

这不应该是:

--------------------------
   a    |  b  |  c

   1    |  2  | 3

  4     |     | 5
但我不知道为什么sql查询会给出:

 a | b | c 

 4 |   | 5
   | 2 | 3
 1 | 2 | 
您的查询:

select *
from t1 natural full outer join
     result
相当于:

select *
from t1 full outer join
     result
     on t1.a = result.a and t1.b = result.b;
natural
join查看所有公共字段,而不仅仅是一个字段。没有匹配的行,这就是为什么会得到三行结果

你似乎想要:

select *
from t1 full outer join
     result
     on t1.b = result.b;

一般来说,最好避免
natural
join,因为它们“隐藏”了有关查询正在执行的操作的信息,并且很容易导致错误/意外的结果。

我不知道您是否知道
完全外部连接的工作原理

FULL-OUTER-JOIN
组合了左侧和右侧外部联接的结果,并返回JOIN子句两侧表中的所有行(匹配或不匹配)

因此,如果您希望得到此结果:

--------------------------
   a    |  b  |  c

   1    |  2  | 3

   4    |     | 5
使用以下表格:

    t1             result
-----------      -----------------
 a  | b           a    |  b  | c

 1  | 2                | 2   | 3

                    4  |     | 5
您应该执行以下查询:

SELECT * FROM t1 natural RIGHT JOIN (result) res ON t1.b = res.b

因为您必须指定必须与哪个列联接。

我删除了MySQL标记,因为它不支持完全外部联接。完全外部联接在MySQL中不存在。如果您想模仿它,请查看以下帖子:
    t1             result
-----------      -----------------
 a  | b           a    |  b  | c

 1  | 2                | 2   | 3

                    4  |     | 5
SELECT * FROM t1 natural RIGHT JOIN (result) res ON t1.b = res.b