如何根据SQL Server select语句中的两列值返回值?

时间:2013-07-01 10:28:19

标签: sql sql-server sql-server-2008

请参阅以下内容以了解我的需求:

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

当我搜索值2时,我希望我的搜索结果返回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 个答案:

答案 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

上的示例