如何使用INSERT INTO和WITH语句执行查询?

时间:2017-10-25 05:32:57

标签: mysql sql

INSERT INTO tablename( columnname1, columnname2, columnaname2)
WITH
a AS
SELECT * FROM tablename
WHERE condition
),
b AS
SELECT * FROM tablename
WHERE condition
)

我在下面有几行查询,我使用DISTINCT语句,但现在想知道上面的查询是否正确。

1 个答案:

答案 0 :(得分:2)

WITH?这将在MySQL 8.0中引入。您使用的是预览版吗?否则你无法在MySQL中使用WITH

无论如何:WITH子句属于语句的开头:WITH ... INSERT ...。见这里:https://dev.mysql.com/doc/refman/8.0/en/with.html

但是,您似乎甚至没有使用CTE ab。您的CTE也缺少括号。例如,你的陈述应该是这样的:

WITH a AS (SELECT * FROM tablename WHERE condition)
   , b AS (SELECT * FROM tablename WHERE condition)
INSERT INTO tablename(columnname1, columnname2, columnaname2)
SELECT col1, col2, col3 FROM a
UNION ALL
SELECT col1, col2, col3 FROM b;