sql表比较-postgres
我有两个表,其中一些列是相同的: 表Asql表比较-postgres,sql,postgresql,Sql,Postgresql,我有两个表,其中一些列是相同的: 表A | Col1 | Col2 | Col3 | +------+------+------+ | 1 | aa | ccc | | 2 | null | ccc | | null | bb | null | 表B |Col1 | Col2 | Col3| Col4 | +------+-------+-----+------+ | 1 | aa | ccc | aaaa | | 2 | null | ccc
| Col1 | Col2 | Col3 |
+------+------+------+
| 1 | aa | ccc |
| 2 | null | ccc |
| null | bb | null |
表B
|Col1 | Col2 | Col3| Col4 |
+------+-------+-----+------+
| 1 | aa | ccc | aaaa |
| 2 | null | ccc | cccc |
| null | bb | null | sss |
| 4 | bb | null | ddd |
我想退回以下物品:
|Col1 | Col2 | Col3| Col4 |
+------+-------+-----+------+
| 4 | bb | null | ddd |
select a.*,
case when b.ctid is null then 'I AM A VERY SAD PENGUIN AND ROW IN B WAS NOT FOUND :('
else b.col4 end as col4
from table_a a
left join table_b b on
((a.col1 = b.col1 or (a.col1 is null and b.col1 is null)) and
(a.col2 = b.col2 or (a.col2 is null and b.col2 is null)) and
(a.col3 = b.col3 or (a.col3 is null and b.col3 is null))
)
如何检查表B
中的哪些行位于表A中,并返回Col4
(来自表B
)它们在查询中匹配的位置。
我使用了,除了
,它工作得很好,但是现在我需要在返回的查询结果中有Col4
的输出
谢谢。像这样的东西
SELECT Col1, Col2, Col3, Col4
FROM TableB
WHERE NOT EXISTS (
SELECT 1
FROM TableA
WHERE TableA.Col1 IS NOT DISTINCT FROM TableB.Col1
AND TableA.Col2 IS NOT DISTINCT FROM TableB.Col2
AND TableA.Col3 IS NOT DISTINCT FROM TableB.Col3
)
(使用与没有区别,可以说为null的列彼此相等。)您的问题的答案非常简单:表“A”中的行都不在表“B”中。
这些是单独的表,它们有单独的行
现在,如果您想在表B中找到一行,该行在列中的值与表a中的特定行相似,您可以执行以下操作:
|Col1 | Col2 | Col3| Col4 |
+------+-------+-----+------+
| 4 | bb | null | ddd |
select a.*,
case when b.ctid is null then 'I AM A VERY SAD PENGUIN AND ROW IN B WAS NOT FOUND :('
else b.col4 end as col4
from table_a a
left join table_b b on
((a.col1 = b.col1 or (a.col1 is null and b.col1 is null)) and
(a.col2 = b.col2 or (a.col2 is null and b.col2 is null)) and
(a.col3 = b.col3 or (a.col3 is null and b.col3 is null))
)
我假设“相似”的意思是“如果两个表中的列中都出现null,则行仍然相似
请注意我添加的表_b中的最后一个插入-不能保证找到col4的唯一值!:
如果b
表中没有重复项,那么下面的NULL
值处理起来相当优雅:
select col1, col2, col3, max(col4)
from ((select coll, col2, col3, null as col4, 'a' as which
from a
) union all
(select coll, col2, col3, col4, 'b' as which
from b
)
) b
group by col1, col2, col3
having min(which) = 'b';
我已经更新了我的表以使事情更清楚。谢谢你在这方面的帮助。更新了我的逻辑,你希望TableB中的行在TableA中不存在,对吗?宾果-这正是我想要的-非常感谢:)这工作非常出色-是否可以更新此sql,以便我可以在case语句中找出哪些列不同。让我们先说TableA.Col1 TableB.Col1,然后说“Col1 different”等等。非常感谢这一点——这非常好——当我向其中添加case语句时,它需要永远运行——是否有任何加速的方法?当我说类似时,我的意思是比较前三列,但返回表b中的行不在表a中的所有四列(仅通过比较前三列)