MySQL为内连接UNION右连接创建一个表

时间:2016-10-03 05:37:31

标签: mysql join union

在我的SQL 5.5中:

尝试创建一个表,该表是表A&的INNER JOIN的结果。表C和表C&(UNION)RIGHT JOIN乙

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

任何一位大师能提供一些建议吗?谢谢。

2 个答案:

答案 0 :(得分: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不应该用括号括起来

答案 1 :(得分: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
);