繁体   English   中英

SQL查询以查找其中1列的值与另一行的另一列匹配的行

[英]SQL query to find rows where 1 column value matches another column on another row

我有一个数据库表,该表的列名为“ symbol”,该列通过非聚集索引是唯一的。 现在,我们需要使用同一表中另一列(例如column2)中的数据来更改“符号”列中的数据。

尝试进行更新,例如

update table
set symbol = column2
where column2 <> '' and
deleted = 0

导致“无法在对象中插入重复的键行”错误,因此表中必须存在1个或多个行,这些行中的符号列中的值已经等于column2中的值,或者某些行具有重复的第2列值。

我可以在column2中找到重复的行,但是我很难找到一个查询来找到那些在column2中任何行中存在的符号列中具有值的行。 任何人有任何想法吗?

谢谢。

select t1.symbol, count(0) as rows
from table t1
join table t2 on t2.column2 = t1.symbol
group by t1.symbol

测试数据:

symbol      column2
----------- -----------
1           1
2           1
3           3
4           5

在column2的任何行中的符号列中找到具有值的行。

select symbol, column2
from table 
where symbol in (select column2
                 from table)

结果:

symbol      column2
----------- -----------
1           1
3           3

或者,这可能取决于您想要的结果。

select symbol, column2
from table as T1
where exists (select *
              from table as T2
              where T1.symbol = T2.column2 and
                    T1.symbol <> T2.symbol)

结果:

symbol      column2
----------- -----------
1           1

暂无
暂无

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

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