SQL反复联接(M:N)

时间:2018-10-06 08:25:14

标签: sql join

如何在SQL中将一个表与另一个表多次连接?说明性示例:

表格“情侣”:

+------+------+------+
|  ID  | ID_1 | ID_2 |
+------+------+------+
|   1  |  123 |  456 |
+------+------+------+

表格“信息”:

+-----+-----------+-----------+--------+--------+
| ID  | FirstName | LastName  | Gender | Season |
+-----+-----------+-----------+--------+--------+
| 123 | Jon       | Snow      | Male   |      6 |
| 456 | Daenerys  | Targaryen | Female |      6 |
| 123 | Jon       | Targaryen | Male   |      7 |
+-----+-----------+-----------+--------+--------+

现在我需要一个组合的结果,该结果必须是“最新的”( Info.Season 必须是最高的,但是您不能删除过时的行):

所需结果:

+-------------+------------+----------+-------------+------------+----------+
| FirstName_1 | LastName_1 | Gender_1 | FirstName_2 | LastName_2 | Gender_2 |
+-------------+------------+----------+-------------+------------+----------+
| Jon         | Targaryen  | Male     | Daenerys    | Targaryen  | Female   |
+-------------+------------+----------+-------------+------------+----------+

我不知道如何解决该问题,ID并不是唯一的,我需要“多次”加入 Info 表。

1 个答案:

答案 0 :(得分:1)

您可以使用SQL窗口函数通过season对每个播放器进行排序,从而选择播放器的最新状态。然后,您需要为夫妇中的每个人将信息表加入到couples表中。

actor_latest CTE

ID  FIRSTNAME   LASTNAME    GENDER  SEASON  LAST_CHANGE
123 Jon         Targaryen   Male    7       1
123 Jon         Snow        Male    6       2
456 Daenerys    Targaryen   Female  6       1

结果SQL

with actor_latest (id, firstname,lastname,gender,season, last_change) as (
    select
        id
      , firstname
      , lastname
      , gender
      , season
      , rank() over (partition by id order by season desc) as last_change
    from info
)
select
    left_partner.firstname as firstname_1
  , left_partner.lastname as lastname_1
  , left_partner.gender as gender_1
  , left_partner.season as season_1
  , right_partner.firstname as firstname_2
  , right_partner.lastname as lastname_2
  , right_partner.gender as gender_2
  , right_partner.season as season_2
from
    couples c
    join actor_latest left_partner on c.id_1 = left_partner.id and left_partner.last_change=1
    join actor_latest right_partner on c.id_2 = right_partner.id and left_partner.last_change=1

结果

FIRSTNAME_1 LASTNAME_1 GENDER_1 SEASON_1 FIRSTNAME_2    LASTNAME_2  GENDER_2 SEASON_2
Jon         Targaryen  Male     7        Daenerys       Targaryen   Female   6

SQL Fiddle