两个具有不同列的表的SQL联合

6

我希望从两个有不同列名的表中获取一组数据行,每个表按行排列。

结果应该如下所示,空白处可以为空,第二部分中的team_id来自coach_id:

-----------------------------------------
player_id | team_id | score | improvement
-----------------------------------------
11          20         5
11          21         4
12          22         2
12          23         2
11          20                   5
11          21                   6
12          21                   5
13          23                   10

以下是模式结构:

这里是模式结构:

CREATE TABLE coaches
    (`id` int, `team_id` int)
;

INSERT INTO coaches
    (`id`, `team_id`)
VALUES
    (1, 20),
    (2, 21),
    (3, 22),
    (4, 23)
;

CREATE TABLE players
 (`id` int, `player_id` int);


INSERT INTO players
(`id`, `player_id`)
VALUES
(1,11),
(2,12),
(3,13),
(4,14)
;
CREATE TABLE games
    (`id` int, `player_id` int, `team_id` int, `score` int)
;

INSERT INTO games
    (`id`, `player_id`, `team_id`, `score`)
VALUES
    (1, 11, 20, 5),
    (2, 11, 21, 4),
    (3, 12, 22, 2),
    (4, 12, 23, 2)
;

CREATE TABLE sessions
    (`id` int, `player_id` int, `coach_id` int, `improvement` int)
;

INSERT INTO sessions
      (`id`, `player_id`, `coach_id`, `improvement`)
VALUES
    (1, 11, 1, 5),
    (2, 11, 2, 6),
    (3, 12, 2, 5),
    (4, 13, 4, 10)
;

尝试了这个方法,但效果并不理想:
SELECT tweets.player_id
      ,tweets.team_id
      ,follows.coach_id 
FROM tweets FULL OUTER JOIN follows ON (1 = 0);

你目前尝试了什么? - Vivek S.
我尝试过的所有方法都没有真正接近。 选择 推文.球员ID,推文.团队ID,关注.教练ID 从 推文 完全外连接 关注 在(1 = 0)上; - mtbomb
1
使用反引号的带引号标识符对于Postgres是无效的,您确定您正在使用Postgres吗?那看起来更像是MySQL。 - user330315
我正在尝试从SQLfiddle设置一个简单的示例。最终我将使用Postgres。 - mtbomb
SQLFiddle支持Postgres。 - user330315
虽然这个问题“容易”,因为实际上表格只有两列不同,而且列数很少,但是它的解决方案并不具有可扩展性。在这里要看的术语实际上是“外连接”(如 https://cs.stackexchange.com/questions/6997/what-is-outer-union-and-why-is-it-partially-compatible)。 - humanityANDpeace
2个回答

4
尝试一下:

尝试执行此操作

 SELECT player_id
    ,team_id
    ,score
    ,NULL AS improvement
FROM games
UNION All
SELECT sessions.player_id
    ,coaches.team_id
    ,NULL AS score
    ,sessions.improvement
FROM sessions
INNER JOIN coaches ON coaches.id = sessions.coach_id

1
然后尝试将分数设为null。 - SimarjeetSingh Panghlia
你在你的环境中测试过吗?我认为没有,因为 UNION 无法帮助你获得精确的结果,所以你需要使用 UNION ALL - Vivek S.
我该如何扩展这个解决方案?假设有4列是特定于UNION的,甚至可能有100列,这是否意味着查询必须插入100个NULL AS列?此外,所有选定的列都需要手动命名,那么SELECT *通配符怎么工作呢? - humanityANDpeace

1

类似于以下内容:

select player_id
     , team_id
     , score
     , cast(null as int) as improvement 
from games 
union all 
select s.player_id
     , c.team_id
     , cast(null as int) as score
     , s.improvement 
from sessions as s 
join coaches as c 
    on s.coach_id = c.id 
order by score

应该可以工作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接