在SQL表上使用什么样的连接

问题描述:

我有3个包含电影数据的表。他们被称为令人震惊,平均和杰出。他们都有列title_types,流派,年份和评级。我试图将所有3个表格合并到一个名为facts的新表格中,使用此提示:在SQL表上使用什么样的连接

仔细考虑此 查询的连接类型,以避免丢失单个表中的记录。

我最初的想法是使用一个完全外部联接,并做一些挖加入所有的表,这是我的代码

CREATE TABLE Facts as 
SELECT Appalling.title_type, Average.title_type, Outstanding.title_type 
FROM Appalling 
FULL OUTER JOIN Average ON Appalling.title_type = Average.title_type 
FULL OUTER JOIN Outstanding ON Appalling.title_type = Outstanding.title_type; 

但是我不知道这是否是加盟的所有表的最聪明的方式。任何帮助表示赞赏。我相信最终的输出应该是这样的:

title_type | genre | year | appalling | average | outstanding 
movie  drama 1992 1   NULL  NULL 
tv   comedy 2001 NULL   15  NULL 
short  drama 2014 NULL   NULL  17 
+0

也许这只是我,但无论是表的设计和加入需求看起来真的很奇怪,'title_types'列包含什么内容? – Matt

+0

@Matt标题类型就像电子游戏,电影,电视系列等。 –

+0

好的,你想如何看最后的输出,我的意思是,你想选择什么专栏? – Matt

这似乎是非常糟糕的数据模式设计。

您应该使用1个表格,只需一列,指示电影是否平均,无效或未完成。

但是,做不到这一点,如果其他列两个表中相似的,你可以使用UNION ALL:(更新所以你仍然可以区分

CREATE TABLE Facts -- Data Types are for demo purposes, I have no idea what you use, use the appropriate data type yourself 
( 
column_types varchar(500), 
title varchar(500), 
genre varchar(500), 
year int, 
rating int, 
ratingType varchar(500) 
); 

INSERT INTO Facts (column_types, title, genre, year, rating, ratingType) 
(
SELECT a.column_types, a.title, a.genre, a.year, a.rating, 'Average' AS ratingType FROM Average AS a 
UNION ALL 
SELECT ap.column_types, ap.title, ap.genre, ap.year, ap.rating, 'Appalling' AS ratingType FROM Appalling AS ap 
UNION ALL 
SELECT o.column_types, o.title, o.genre, o.year, o.rating, 'Outstanding' AS ratingType FROM Outstanding AS o 
); 
+0

我同意。我遇到的一个问题是,我的专栏不再区分惊人的,平均的和杰出的。任何提示修复此问题? –

+1

很容易,让我编辑我的答案@CuriousStudent – Magisch

+0

我编辑了我的主帖,你认为这样设计的结构会更好吗? –