[英]sql query for extracting values from one column where other value columns are same
[英]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?
因此,如果我有一個數據庫,其中有一個像這樣的表人:
Person:
id: (unique)
name
以及創建行之間關系的第二個表,如下所示:
Friend:
person1 (foreign key to Person.id)
person2 (foreign key to Person.id)
我如何為這樣的人查詢朋友:
select (other person) from Friend where person1=(me) or person2=(me);
您可以使用 CASE 子句。 例如,如果您要查找 id = 5 的人的所有朋友...
SELECT CASE
WHEN person1 = 5 THEN person2 ELSE person1 END AS friendId
FROM Friend
WHERE (person1 = 5) OR (person2 = 5)
當然,您將使用一個變量,我將其硬編碼為 5。
我知道 person2 和 person1 是朋友
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'
或者
where b.id = 5
如果您想選擇您的朋友,請寫下以下請求:
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
在 Postgres 中,您可以使用橫向連接:
select v.otherperson
from friend f cross join lateral
(values (person1, person2), (person2, person1)) v(me, otherperson)
where v.me = 5;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.