简体   繁体   中英

How to query a pair like table structure?

Before Query

User   Friend

A      B
A      C
D      A
F      A

After Query

User   Friend

A      B
A      C
A      D
A      F

How can I get the result shown. I want to get all friends of A.

With a union:

select user, friend 
from t
where user = 'A'
union 
select friend, user
from t
where friend = 'A'

Notice than Union behavior is distinct that is that you expect ( opposed to union all )

Try this

SELECT  USER AS 'User',
        friend AS 'Friend'
FROM    t
WHERE   USER = 'A'
UNION
SELECT  friend ,
        USER
FROM    t
WHERE   friend = 'A'

没有UNION

SELECT CASE WHEN [User]='A' THEN [user] ELSE [friend] END as [A], CASE WHEN [User]='A' THEN [friend] ELSE [user] END AS [Friend Of A] WHERE [user]='A' OR [friend]='A'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM