gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 11:45:16 25 4
gpt4 key购买 nike

我想从两个具有不同列名的表中获取一组行的结果,每个表中每行一行。

结果应该是这样的,空格可以为空,下半场的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);

最佳答案

取消这个

 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

关于具有不同列的两个表的 SQL 并集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29764499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com