我需要一个SQL查询来比较两个值并返回一个ID。
我有这张桌子:
ID Calling_ID Called_ID
1 27 10
2 15 20
3 80 90
4 90 88
5 60 30
6 88 40
7 15 60
8 30 40
9 27 95
10 40 30
如何检查Calling_ID
列中Called_ID
列中的每个值是否都存在,然后返回ID?以上数据将返回88,30,40。
答案 0 :(得分:17)
这应该有效:
SELECT ID FROM [TableName]
WHERE Calling_ID IN
(
SELECT Called_ID FROM [TableName]
)
答案 1 :(得分:0)
试试这个,
SELECT Calling_ID FROM [Table] where Calling_ID = Called_ID;
答案 2 :(得分:0)
SELECT ID,Calling_ID FROM [Table]
where Calling_ID in (SELECT Called_ID FROM [Table])
答案 3 :(得分:0)
这应该这样做:
SELECT DISTINCT t1.ID FROM [Table] as t1
JOIN [Table] as t2 ON t1.Calling_ID = t2.Called_Id
答案 4 :(得分:0)
根据您的陈述,"以上数据将返回88,30,40,"您似乎在寻找要返回的Calling_ID
/ Called_ID
,而不是ID
。以下是两种完全正确的方法:
使用JOIN
SELECT DISTINCT t1.Calling_ID FROM [Table] AS t1
JOIN [Table] AS t2 ON t1.Calling_ID = t2.Called_Id
使用IN
SELECT DISTINCT Calling_ID FROM [Table]
WHERE Calling_ID IN (SELECT Called_ID FROM [Table])