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

时间:2017-03-09 16:48:38

标签: mysql sql

我的桌子:

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

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

1)我想获取友谊表中包含某个personid的所有行。此id可以在person1或person2列中。应保留fid列,但person列应仅为1,例如:

 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的结果中加入人员表。

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您需要所有人的每个朋友的名字和姓氏,无论此人是在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'

答案 1 :(得分:1)

对于第一步,在where过滤器中使用OR子句来指示应保留哪些记录。然后在你的选择中使用case语句来选择哪个人。

select    fid
        , case person1 when some_personid then person1 else person2 end as person
    from friendships
    where (person1 = some_personid
        or person2 = some_personid)

对于第二步,您从人员中选择并使用子查询从步骤1加入到表中。

select *
    from persons p
    inner join (
        select    fid
                , case person1 when some_personid then person1 else person2 end as person
            from friendships
            where (person1 = some_personid
                or person2 = some_personid)
    ) f on f.person = p.pid

希望这有帮助!