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

标签 mysql join union

在我的 SQL 5.5 中:

尝试创建一个表,该表是表 A 和 B 的 INNER JOIN 以及表 C 和 B 的 (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

有哪位高手可以给点建议吗?谢谢。

最佳答案

请尝试以下操作:

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 不应用括号括起来

关于MySQL为内连接UNION右连接创建表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39825149/

相关文章:

mysql - 使用 1 :n in different column 重复 SQL 表中的每个值 n 次

MySQL - 比较两个表的值并记录它们

php - 查询在脚本中返回空集,适用于 PHPMyAdmin 和本地版本

mysql - 带条件和的内连接

php - codeigniter 加入多对多 LIMIT

SQLite3 使用 LEFT JOIN 和 UNION 模拟 RIGHT OUTER JOIN

字段名相同时的SQL连接

mysql - SQL Join涉及3张表,怎么办?

MySQL 左连接重复行计数和

mysql连接同一个表不同的结果集