具有不同列的两个表的SQL并集

具有不同列的两个表的SQL并集,sql,postgresql,Sql,Postgresql,我想从两个具有不同列名的表中返回一个结果行集,每个表中每行一行 结果应该是这样的,空格可以为空,下半场的球队id来自教练id: ----------------------------------------- player_id | team_id | score | improvement ----------------------------------------- 11 20 5 11 21 4 12

我想从两个具有不同列名的表中返回一个结果行集,每个表中每行一行

结果应该是这样的,空格可以为空,下半场的球队id来自教练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);
这真是愚蠢

 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
比如:

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

到目前为止,你已经尝试过了吗?我尝试过的都不是很成功。选择tweets.player_id、tweets.team_id、follows.coach_id FROM tweets FULL OUTER JOIN follows ON(1=0);使用倒勾的带引号的标识符对Postgres无效您确定要使用Postgres吗?这看起来更像MySQL。我试图从SQLFIDLE中建立一个简单的示例。我最终将使用PostgresSQLFiddle来支持Postgres,然后尝试null作为分数。您在您的环境中测试过吗?我不这么认为,因为
UNION
无法帮助您获得准确的结果,所以您需要使用
UNION ALL
如何扩展此解决方案?假设有4列是
联合
的特殊列,甚至是100列,这是否意味着查询必须将100
NULL作为
列插入?此外,所有选定的列都需要手动命名,
SELECT*
通配符如何工作?