SQL 查询有关 OUTER JOIN 的帮助吗?
我有两张这样的桌子。
Table1
Column | Type |
---------+------------------+
cod | text |
value99 | double precision |
Table2
Column | Type |
---------+------------------+
cod | text |
value06 | double precision |
和我想加入它们,所以我有类似的
Column | Type |
---------+------------------+
cod | text |
value99 | double precision |
value06 | double precision |
问题是,并非所有代码都存在于两个表中,因此,如果代码不存在于其中一个表中,则其值应该为空。最后我想要这样的东西
cod | value99 | value06 |
---------+------------------+------------------+
1 | 10 | 20 |
2 | 13 | NULL |
3 | NULL | 15 |
我认为使用左或右连接是不可能的..或者也许是...有什么想法吗?谢谢=)
编辑: 我已经尝试过 FULL OUTER JOIN 但结果类似于
code value code value
1 10 1 4
2 15 NULL NULL
NULL NULL 3 36
ANSWER!!!: 我找到了答案,谢谢@Tobiasopdenbrouw:
SELECT test1.code,test1.value,test2.value FROM public.test1 LEFT OUTER JOIN public.test2 ON test1.code=test2.code
UNION
SELECT test2.code,test1.value,test2.value FROM public.test1 RIGHT OUTER JOIN public.test2 ON test1.code=test2.code
I have two tables like this.
Table1
Column | Type |
---------+------------------+
cod | text |
value99 | double precision |
Table2
Column | Type |
---------+------------------+
cod | text |
value06 | double precision |
and i'd like to join them so i'd have something like
Column | Type |
---------+------------------+
cod | text |
value99 | double precision |
value06 | double precision |
the problem is that not all the codes are present in both tables, so if a code is not present in one of the tables it's value should be null.. In the end i'd like something like this
cod | value99 | value06 |
---------+------------------+------------------+
1 | 10 | 20 |
2 | 13 | NULL |
3 | NULL | 15 |
I think that its not possible using LEFT or RIGHT JOIN.. or maybe it is... any ideas? Thx=)
EDITED:
I've tried the FULL OUTER JOIN but the result is something like
code value code value
1 10 1 4
2 15 NULL NULL
NULL NULL 3 36
ANSWER!!!:
i found the answer thx to @Tobiasopdenbrouw :
SELECT test1.code,test1.value,test2.value FROM public.test1 LEFT OUTER JOIN public.test2 ON test1.code=test2.code
UNION
SELECT test2.code,test1.value,test2.value FROM public.test1 RIGHT OUTER JOIN public.test2 ON test1.code=test2.code
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我猜测了一下,因为您的问题没有详细描述所需的输出,但您可能需要的是一个辅助查询,它将为您创建一个包含所有代码的表(一个
UNION
2 个SELECT
查询)。然后可以将该辅助表LEFT JOINED
连接到您的 2 个源表)。编辑:我自己想到了(完整)外部连接答案,但在阅读字里行间时,我认为这并不是OP真正需要的。但当然,我也可能是错的。
I'm guessing a bit, because your question doesn't describe the required output in great detail, but what you probably need is a helper query that will create a table with all the codes for you (a
UNION
of 2SELECT
querys). This helper table can then beLEFT JOINED
to your 2 source tables).Edit: I thought of the (FULL) OUTER JOIN answer myself, but in reading between the lines, I don't think that's what the OP really needs. But I can be wrong, of course.
使用完全外部连接。
Use a FULL OUTER JOIN.