尝试在 MySQL 中创建 CTE 时出现语法错误

Getting a Syntax Error when Trying to Create a CTE in MySQL

代码如下:

WITH sub_query AS (Select imdp_title_id FROM movie_ratings) 

这是输出:

Error Code: 1064. 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 '' at line 1

MySQL 版本:'8.0.26'

使用的软件:MySQL Workbench 8.0

提前致谢。

使用 CTE 语法时,必须定义 CTE,然后在 DML 语句中使用该 CTE。

https://dev.mysql.com/doc/refman/8.0/en/with.html 说:

The following example defines CTEs named cte1 and cte2 in the WITH clause, and refers to them in the top-level SELECT that follows the WITH clause:

WITH
  cte1 AS (SELECT a, b FROM table1),
  cte2 AS (SELECT c, d FROM table2)
SELECT b, d FROM cte1 JOIN cte2
WHERE cte1.a = cte2.c;

这表明您在一个或多个 <cte> AS ( <subquery> ) 定义之后有一个最终的 SQL 语句。

MySQL 8.0 支持 CTE 之后的 SELECTUPDATEDELETE DML 语句。