简体   繁体   中英

Custom sql query

Say i have an image :

在此处输入图片说明

This signifies that 1 has friends 2,3,4 and 6 is also the friend of 1.

How do i get these ids 2,3,4 and 6 that are friends with 1 using SQL

that depends a bit on which DB you are using - the following will work in MySQL and Oracle and perhaps in MS SQL server (not sure):

SELECT 
(CASE WHEN ID1 = 1 THEN ID2 ELSE ID1 END) AS THEFRIENDS 
FROM YOURTABLE WHERE 
ID2 = 1 OR 
ID1 = 1

This one works everywhere but is perhaps less performant:

SELECT ID1 FROM YOURTABLE WHERE ID2 = 1
UNION
SELECT ID2 FROM YOURTABLE WHERE ID1 = 1
select id2 as FriendID from table
where id1 = 1
union
select id1 as FriendID from table
where id2 = 1

为初学者使用更多描述性名称

SELECT * FROM table WHERE id1=1 or id2=1 and id1<>id2

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