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

标签 mysql sql

我的 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/

相关文章:

php - 使用列值作为 mysql 中另一列的标题

MySQL索引问题,中大型表上相对少量索引行的简单查询耗时过长

mysql - 使用 Bash 脚本通过变量将 bool 值插入 MySql

php - 10页pdf可以只显示2页吗?

sql - 如何在事务中短暂破坏引用完整性而不禁用外键约束?

java - 如何在 java 中实现类似 'LIKE' 运算符的 SQL?

mysql - 在 MySQL 中存储和访问庞大数据矩阵的最有效方法

sql - 如何连续获得员工的所有拳头?

sql - TSQL 返回存在的内容

sql - 如何使用安装程序/更新脚本和 Magento 抽象更新 Magento 产品的值?