[英]SQL union of two tables with different columns
我想從具有不同列名的兩個表中返回一行結果集,每個表中的每一行一行。
結果應如下所示,空格可以為null,第二半的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);
nulnullry這
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
應該管用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.