4

请参阅下面以了解我想要什么:

------------------------------
   Friend       | User 
------------------------------
     2          |  1 
     3          |  2 
     2          |  5
     4          |  2 
------------------------------

当我搜索 value时,我希望我的搜索结果在and2中返回相关值,如下所示:FriendUser

--------------------------
      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 查询来完成此操作?

4

4 回答 4

8
SELECT Friend FROM MyTable WHERE User = 2
UNION
SELECT User FROM MyTable WHERE Friend = 2;
于 2013-07-01T10:32:00.990 回答
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
于 2013-07-01T10:37:47.553 回答
1
select case Friend when 2 then User else Friend end
FROM table 
where User = 2 
or Friend = 2;
于 2013-07-01T10:34:00.920 回答
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

于 2013-07-01T10:41:31.577 回答