检查SQL中另一列中是否存在列值

时间:2022-10-01 07:58:44

I need a SQL query that compares two values and returns an ID.

我需要一个比较两个值并返回ID的SQL查询。

I have this table:

我有这张桌子:

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

How do I check if each value in the Calling_ID column exists in the Called_ID column and then return the ID? The above data would return 88, 30, 40.

如何检查Callled_ID列中的每个值是否存在于Called_ID列中,然后返回ID?以上数据将返回88,30,40。

5 个解决方案

#1


9  

This should work:

这应该工作:

SELECT ID FROM [TableName]
WHERE Calling_ID IN
(
SELECT Called_ID FROM [TableName]
)

#2


0  

Try this,

尝试这个,

SELECT Calling_ID FROM [Table] where Calling_ID = Called_ID;

#3


0  

SELECT ID,Calling_ID FROM [Table]
where Calling_ID in (SELECT Called_ID FROM [Table])

#4


0  

This should do it:

这应该这样做:

SELECT DISTINCT t1.ID FROM [Table] as t1 
JOIN [Table] as t2 ON t1.Calling_ID = t2.Called_Id

#5


0  

Based on your statement, "The above data would return 88, 30, 40," it seems you were looking for Calling_ID / Called_ID to be returned, not ID. Here are two fully correct ways to do that:

根据您的陈述,“上述数据将返回88,30,40”,您似乎在寻找要返回的Calling_ID / Called_ID,而不是ID。以下是两种完全正确的方法:

Using JOIN

使用JOIN

SELECT DISTINCT t1.Calling_ID FROM [Table] AS t1 
JOIN [Table] AS t2 ON t1.Calling_ID = t2.Called_Id

Using IN

使用IN

SELECT DISTINCT Calling_ID FROM [Table]
WHERE Calling_ID IN (SELECT Called_ID FROM [Table])

#1


9  

This should work:

这应该工作:

SELECT ID FROM [TableName]
WHERE Calling_ID IN
(
SELECT Called_ID FROM [TableName]
)

#2


0  

Try this,

尝试这个,

SELECT Calling_ID FROM [Table] where Calling_ID = Called_ID;

#3


0  

SELECT ID,Calling_ID FROM [Table]
where Calling_ID in (SELECT Called_ID FROM [Table])

#4


0  

This should do it:

这应该这样做:

SELECT DISTINCT t1.ID FROM [Table] as t1 
JOIN [Table] as t2 ON t1.Calling_ID = t2.Called_Id

#5


0  

Based on your statement, "The above data would return 88, 30, 40," it seems you were looking for Calling_ID / Called_ID to be returned, not ID. Here are two fully correct ways to do that:

根据您的陈述,“上述数据将返回88,30,40”,您似乎在寻找要返回的Calling_ID / Called_ID,而不是ID。以下是两种完全正确的方法:

Using JOIN

使用JOIN

SELECT DISTINCT t1.Calling_ID FROM [Table] AS t1 
JOIN [Table] AS t2 ON t1.Calling_ID = t2.Called_Id

Using IN

使用IN

SELECT DISTINCT Calling_ID FROM [Table]
WHERE Calling_ID IN (SELECT Called_ID FROM [Table])