gpt4 book ai didi

mysql - 将两列合二为一,同时保留其他列。然后与另一个表合并

转载 作者:行者123 更新时间:2023-11-29 07:03:02 25 4
gpt4 key购买 nike

我的 table :

//             friendships
+-----------------+-----------------+-----------------+
| fid | person1 | person2 |
|-----------------+-----------------|-----------------+
+-----------------+-----------------+-----------------+
| 1 | personid | personid |
|-----------------+-----------------|-----------------+
| 2 | personid | personid |
|-----------------+-----------------|-----------------+

// persons
+-----------------+-----------------+-----------------+
| pid | firstname | lastname |
|-----------------+-----------------|-----------------+
+-----------------+-----------------+-----------------+
| 1 | name | name |
|-----------------+-----------------|-----------------+
| 2 | name | name |
|-----------------+-----------------|-----------------+

1 ) 我想获取 Friendship 表中包含某个 personid 的所有行。此 ID 可以位于 person1 或 person2 列中。应保留 fid 列,但 person 列只能是一个,例如:

 Select fid, person1 as person, person2 as person FROM friendships
WHERE person1 = some_personid
OR person2 = some_personid;

(此查询中的 2 人列应该只有一个)。我该怎么做?

2) 我想将步骤 1 ON fid.person = Persons.pid 的结果加入到 Persons 表中。

最佳答案

如果我理解正确的话,您需要所需人员的每个 friend 的名字和姓氏,无论此人属于 person1 还是 person2

在这种情况下,如果友谊关系不对称,您可以使用子查询来实现

select  *
from persons p
join (
select fid, person1 as person, person2 as otherPerson
from friendship
where person1 = 'yourPerson'
union all
select fid, person2 as person, person1 as otherPerson
from friendship
where person2 = 'yourPerson'
) f
on p.pid = f.otherPerson

如果是对称的,则查询会更容易,因为 person2 下包含所需人员的每一行都将在 person1 下具有包含所需人员的对应行。

select  *
from friendship f
join person p
on f.person2 = p.pid
where person1 = 'yourPerson'

关于mysql - 将两列合二为一,同时保留其他列。然后与另一个表合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42700966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com