简体   繁体   中英

How to select 1 of two column values from a row where one is a value your query and the other you want in SQL?

So if I had a database where there was a table person like so:

Person:
  id: (unique)
  name

And a second table that created relationships between rows like so:

Friend:
  person1 (foreign key to Person.id)
  person2 (foreign key to Person.id)

How would I query friends for a person like so:

select (other person) from Friend where person1=(me) or person2=(me);

You could use a CASE clause. For example, if you're looking for all persons who are friends of person with id = 5...

SELECT CASE 
   WHEN person1 = 5 THEN person2 ELSE person1 END AS friendId
FROM Friend 
WHERE (person1 = 5) OR (person2 = 5)

Naturally you'll use a variable where I'm hard-coding a value of 5.

I understand that person2 and person1 are friends

select a.person2 from 
(
select person1, person2 from Friend union select person2, person1 from Friend 
)
a inner join Person b where b.id = a.person1 
where b.name = 'nameofPersonne'

or

 where b.id = 5

If you like to select your friends write this following request:

select isnull(f1.person2, f2.person1)
from person p
left join friend f1 on p.id = f1.person1
left join friend f2 on p.id = f2.person2
join friend f on p.id = f.person1 or p.id = f.person2
where p.id = you

In Postgres, you can use a lateral join:

select v.otherperson
from friend f cross join lateral
     (values (person1, person2), (person2, person1)) v(me, otherperson)
where v.me = 5;

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