简体   繁体   English

如何从一行中选择两个列值中的一个,其中一个是您的查询值,另一个是您在 SQL 中想要的值?

[英]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.您可以使用 CASE 子句。 For example, if you're looking for all persons who are friends of person with id = 5...例如,如果您要查找 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.当然,您将使用一个变量,我将其硬编码为 5。

I understand that person2 and person1 are friends我知道 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'

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:在 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.

相关问题 sql查询从其中其他值列相同的一列中提取值 - sql query for extracting values from one column where other value columns are same SQL选择行,其中(此列中的其他值很多) - SQL select row where (this column has many different values in the other) 选择SQL中在一行中具有列值而不在另一列中具有特定其他列值的值 - Select values in SQL that have a colum value in one row and not a specific other column value in another 如何从具有相同值的两个不同列中选择一行 - How select one row from two distinct column with same value Access SQL查询:使两个列具有相同的值,但是如何排除列1 =列2的情况? - Access SQL Query: Making two columns of the same values, but how do you exclude cases where column 1 = column 2? SELECT行值WHERE MAX()是GROUP BY查询中的列值 - SELECT Row Values WHERE MAX() is Column Value In GROUP BY Query [SQL]一个选中的列和两个值,在一行中选中它们 - [SQL]One selected column and two values, select them in a row SQL选择行,其值介于两个列值之间 - SQL Select row with value between two column values (SQL)您如何 select 一个最大浮点值以及查询中的其他数据类型值? - (SQL) How do you select a max float value along with other datatypes values within a query? 我想在 SQL 中将行值查询为列 - I want to query the row values as Column in SQL
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM