2012-03-20 49 views
2

我有一个名为'symbol'的列的数据库表,它通过非聚集索引是唯一的。 我们现在需要使用来自同一个表中另一列的数据(比如column2)更改'符号'列中的数据。SQL查询来查找行列值与另一行上的另一列匹配的行

尝试进行更新

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

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

我可以在列2中找到具有重复项的行,但我努力想出一个查询来查找在列2中任何行中存在的符号列中具有值的行。任何人有任何想法?

谢谢。

回答

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

测试数据:

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 
相关问题