[英]SQL query to find rows where 1 column value matches another column on another row
I have a database table with a column called 'symbol', that is unique via a non-clustered index. 我有一个数据库表,该表的列名为“ symbol”,该列通过非聚集索引是唯一的。 We now need to change the data in the 'symbol' column, using the data from another column in the same table, say column2.
现在,我们需要使用同一表中另一列(例如column2)中的数据来更改“符号”列中的数据。
Trying to do an update, eg 尝试进行更新,例如
update table
set symbol = column2
where column2 <> '' and
deleted = 0
results in a 'Cannot insert duplicate key row in object' error, so there must be 1 or more rows existing in the table that already have a value in the symbol column that is equal to the value in column2, or there are some rows that have a duplicate column 2 value. 导致“无法在对象中插入重复的键行”错误,因此表中必须存在1个或多个行,这些行中的符号列中的值已经等于column2中的值,或者某些行具有重复的第2列值。
I can find the rows that have duplicates in column2, but I'm struggling to come up with a query to find those rows that have a value in the symbol column that exists in any row in column2. 我可以在column2中找到重复的行,但是我很难找到一个查询来找到那些在column2中任何行中存在的符号列中具有值的行。 Any one got any ideas?
任何人有任何想法吗?
Thanks. 谢谢。
select t1.symbol, count(0) as rows
from table t1
join table t2 on t2.column2 = t1.symbol
group by t1.symbol
Test data: 测试数据:
symbol column2
----------- -----------
1 1
2 1
3 3
4 5
find those rows that have a value in the symbol column that exists in any row in column2.
在column2的任何行中的符号列中找到具有值的行。
select symbol, column2
from table
where symbol in (select column2
from table)
Result: 结果:
symbol column2
----------- -----------
1 1
3 3
Or possibly this depending on what result you want. 或者,这可能取决于您想要的结果。
select symbol, column2
from table as T1
where exists (select *
from table as T2
where T1.symbol = T2.column2 and
T1.symbol <> T2.symbol)
Result: 结果:
symbol column2
----------- -----------
1 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.