2016-10-03 75 views
0

以我SQL 5.5:的MySQL創建一個表內部聯接UNION右連接

試圖建立一個表,該表是一個INNER的結果JOIN表的& B,和(UNION)RIGHT JOIN表的ç& B.

Please see the image for the logic

CREATE TABLE IF NOT EXISTS TABLE_NAME AS (

(SELECT a.column1, b.column2 FROM TABLEA AS a 

INNER JOIN TABLEB AS b 

ON a.column1 = b.column1) 

UNION 

(SELECT c.column1, b.column2 FROM TABLEC AS c 

RIGHT JOIN TABLEB AS b 

ON b.column1 = c.column1) 

); 

錯誤:

ERROR 1064 (42000) at line 11: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(SELECT a.column1, b.column2 FROM TABLEA AS a 

其他嘗試:

CREATE TABLE IF NOT EXISTS TABLE_NAME AS (

(SELECT a.column1, b.column2 FROM TABLEA AS a 

INNER JOIN TABLEB AS b 

ON a.column1 = b.column1) 

UNION 

(SELECT c.column1, b.column2 FROM TABLEC AS c 

RIGHT JOIN TABLEB AS b 

ON b.column1 = c.column1) 

); 

Error: 

ERROR 1064 (42000) at line 11: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UNION 

可以在任何大師提供一些建議?謝謝。

+0

從維恩圖,我想你需要'LEFT JOIN',不'RIGHT JOIN'。 –

回答

0

嘗試,而不是執行以下操作:

CREATE TABLE IF NOT EXISTS TABLE_NAME AS 

(SELECT a.column1, b.column2 FROM TABLEA AS a 

INNER JOIN TABLEB AS b 

ON a.column1 = b.column1) 

UNION 

(SELECT c.column1, b.column2 FROM TABLEC AS c 

RIGHT JOIN TABLEB AS b 

ON b.column1 = c.column1) 

See Demo


documentation

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name 
    [(create_definition,...)] 
    [table_options] 
    [partition_options] 
    [IGNORE | REPLACE] 
    [AS] query_expression 
報價

query_expression不應該用括號

被封閉
+0

可悲的是這不起作用:/。它只是說在下一步中創建的表不存在。我也嘗試過「CREATE TABLE IF NOT EXISTS TABLE_NAME(select ....」,並且它返回相同的錯誤信息 – Chubaka

+0

你能否看看這個演示?http://sqlfiddle.com/#!9/16245f/1/0 @ Chubaka – 1000111

+0

Hi @ 1000111,感謝2美分我實際上是在MySQL 5.5中,如果我們將小提琴更改爲MySQL 5.5,構建模式將顯示未知錯誤:/ – Chubaka

0

試試這個

CREATE TABLE IF NOT EXISTS TABLE_NAME AS 
(
SELECT S.* 
FROM 
(
SELECT a.column1, b.column2 FROM TABLEA AS a 
INNER JOIN TABLEB AS b ON a.column1 = b.column1 
UNION 
SELECT c.column1, b.column2 FROM TABLEC AS c 
RIGHT JOIN TABLEB AS b ON b.column1 = c.column1 
) S 
); 
+0

不幸的是,一個不起作用。它只是在第11行返回「錯誤1146(42S02):TABLE_NAME不存在」。 – Chubaka

+0

嗯。我測試了這一點,它工作正常。你至少會注意到語法錯誤已經消失。 –

+0

Hi @ P.Salmon,你在MySQL 5.5嗎? – Chubaka