请参阅以下内容以了解我的需求:
------------------------------
Friend | User
------------------------------
2 | 1
3 | 2
2 | 5
4 | 2
------------------------------
当我搜索值2
时,我希望我的搜索结果返回Friend
和User
中的相关值,如下所示:
--------------------------
Friends of 2
--------------------------
1 - (from column User )
3 - (from column Friend)
5 - (from column user )
4 = (from column friend )
我想要一个列搜索结果如下:
--------------------------
Friends of 2
--------------------------
1
3
5
4
如何通过在SQL Server中使用SELECT查询来实现此目的?
答案 0 :(得分:8)
SELECT Friend FROM MyTable WHERE User = 2
UNION
SELECT User FROM MyTable WHERE Friend = 2;
答案 1 :(得分:1)
select case Friend when 2 then User else Friend end
FROM table
where User = 2
or Friend = 2;
答案 2 :(得分:1)
Create Table #MyTable(id int identity,FriendID int,UserID int)
Insert into #MyTable values(2,1),(3,2),(2,5),(4,2)
Declare @SearchUserID int=2
select (Case Friendid when @SearchUserID then userID else FriendID end) as [Friends] from #MyTable where @SearchUserID in(Friendid,UserID)
drop Table #MyTable
答案 3 :(得分:0)
COALESCE表达式的另一个选项
SELECT COALESCE(CASE WHEN t.Friend = 2 THEN t.[User] END,
CASE WHEN t.[User] = 2 THEN t.Friend END) AS [Friends of 2]
FROM dbo.Friend t
WHERE t.Friend = 2 OR t.[User] = 2
请参阅SQLFiddle