简体   繁体   English

SQL 查询用于选择单个表中 2 个相关列之间的更改

[英]SQL query for selecting changes between 2 related columns in a single table

Is there a query that can select the rows where a change occurred between 2 related columns that hold different values?是否有一个查询可以 select 在两个相关列之间发生更改的行包含不同的值?

To illustrate:为了显示:

I have ONE table where there is an alphanumeric code, and another column to store its encrypted equivalent.我有一个表,其中有一个字母数字代码,还有另一列存储其加密的等价物。

I need to find the rows where these 2 don't match.我需要找到这两个不匹配的行。 So if I have the following table "codes"所以如果我有下表“代码”

code | encryption
A1   | jl2
A1   | jl2
A1   | ki4
B2   | jl2

I want a query to select the rows where A1 resulted in ki4 and B2 resulted in jl2, because these 2 did not match to their usual results (A1 should always be jl2 and viceversa)我想查询 select A1 导致 ki4 和 B2 导致 jl2 的行,因为这 2 与其通常的结果不匹配(A1 应该始终是 jl2,反之亦然)

The codes are just examples of course, so I cannot just write a query that looks for these exact instances.当然,这些代码只是示例,所以我不能只编写一个查询来查找这些确切的实例。

You can use not exists to get a list of the rows that don't have matches:您可以使用not exists来获取不匹配的行的列表:

select distinct code, encryption
from t
where not exists (select 1
                  from t t2
                  where t2.code = t.code and
                        t2.encryption <> t.encryption
                 );

For those interested in an answer, I think this actually got it done.对于那些对答案感兴趣的人,我认为这实际上已经完成了。 Basically compare the table to itself once and then select the instances where the other column doesnt match基本上将表与自身比较一次,然后 select 另一列不匹配的实例

select a.code,a.encryption,b.encryption
from codes a, codes b
where a.code = b.code
and a.encryption <> b.encryption

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM