2017-10-20 31 views
0

我有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

這似乎是非常糟糕的數據模式設計。

您應該使用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

我編輯了我的主帖,你認爲這樣設計的結構會更好嗎? –