使用 SQL 在数据库 table 中查找不存在匹配键的匹配行

Find matching rows in database table using SQL where no matching key is present

我有一个包含遗留数据和大约 10,000 行的旧 table 和一个包含大约 500 行的新 table。两个 table 中的列相同。我需要将新 table 中的几列与旧列进行比较,并报告新 table.

中重复的数据

我研究了具有类似问题的文章,尝试了 table 连接和 where exists / where not exists 子句,但我无法正确地 SQL。我已经包含了我的最新版本。

我认为给我带来麻烦的一个问题是 table.

中没有像用户 ID 或类似唯一标识符这样的“密钥”

我想要做的是在“新”table 中找到数据,其中除“reference_number”(不管是否存在)之外的所有行都是重复,即已经存在于“旧”table.

到目前为止我有这个...

select 
old.reference_number
new.reference_number
new.component
new.privileges
new.protocol
new.authority
new.score
new.means
new.difficulty
new.hierarchy
new.interaction
new.scope
new.conf
new.integrity
new.availability
new.version
from old, new
where
old.component = new.component
old.privileges = new.privileges
old.protocol = new.protocol
old.authority = new.authority
old.score = new.score
old.means = new.means
old.difficulty = new.difficulty
old.hierarchy = new.hierarchy
old.interaction = new.interaction
old.scope = new.scope
old.conf = new.conf
old.integrity = new.integrity
old.availability = new.availability
old.version = new.version

我在这里试过了,但由于某种原因它似乎没有提取所有数据。

很明显,旧 table 中实际上有更多行在新 table 中重复,但我只从查询中返回少量行。

任何人都可以找出为什么会这样吗,还有其他方法可以解决这个问题吗?

如果重要的话,这是 Postgresql。

感谢您提供的任何帮助。

下面应该做你想做的:

select distinct o.reference_number,
                n.reference_number,
                n.component,
                n.privileges,
                n.protocol,
                n.authority,
                n.score,
                n.means,
                n.difficulty,
                n.hierarchy,
                n.interaction,
                n.scope,
                n.conf,
                n.integrity,
                n.availability,
                n.version
  from new n
  inner join old o
    on o.component = n.component and
       o.privileges = n.privileges and
       o.protocol = n.protocol and
       o.authority = n.authority and
       o.score = n.score and
       o.means = n.means and
       o.difficulty = n.difficulty and
       o.hierarchy = n.hierarchy and
       o.interaction = n.interaction and
       o.scope = n.scope and
       o.conf = n.conf and
       o.integrity = n.integrity and
       o.availability = n.availability and
       o.version = n.version

您应该使用左联接,然后 select 只有具有新值的行为空。 sql 应该是这样的:

select 
old.reference_number
new.reference_number
new.component
new.privileges
new.protocol
new.authority
new.score
new.means
new.difficulty
new.hierarchy
new.interaction
new.scope
new.conf
new.integrity
new.availability
new.version
from old 
  left join new
  on
old.component = new.component
old.privileges = new.privileges
old.protocol = new.protocol
old.authority = new.authority
old.score = new.score
old.means = new.means
old.difficulty = new.difficulty
old.hierarchy = new.hierarchy
old.interaction = new.interaction
old.scope = new.scope
old.conf = new.conf
old.integrity = new.integrity
old.availability = new.availability
old.version = new.version
where new.component is null