为什么 CTE 的工作方式与 MySQL 中的子查询不同?

问题描述 投票:0回答:1

我尝试删除所有type_name以D开头的商品

假设我想从牙科、美食、飞镖游戏类型中删除商品。 因此,我检查 type 是否在列表 d_goods_ids 中(typegood_type_id 的 FK)。

WITH d_goods_ids AS (SELECT good_type_id FROM GoodTypes 
                 WHERE GoodTypes.good_type_name LIKE "d%")

DELETE FROM Goods
WHERE type IN d_goods_ids;

SELECT * FROM Goods;

但是 MySQL 抛出错误:

ER_PARSE_ERROR: 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 'd_goods_ids; SELECT * FROM Goods' at line 5

如果我使用子查询,一切都会完美运行:

DELETE FROM Goods
WHERE type IN (SELECT good_type_id FROM GoodTypes 
               WHERE GoodTypes.good_type_name LIKE "d%");

SELECT * FROM Goods;

在这种情况下,两种变体不应该发挥相同的作用吗?

sql mysql database common-table-expression
1个回答
0
投票

您可以在子查询中引用 CTE,但不像您尝试那样做。

WITH d_goods_ids AS (SELECT good_type_id FROM GoodTypes
                 WHERE GoodTypes.good_type_name LIKE "d%")

DELETE FROM Goods
WHERE type IN (SELECT good_type_id FROM d_goods_ids);

在此示例中,CTE 位于子查询中,在

FROM
子句中引用,就好像它是表名称一样。

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

cte_name
命名单个公用表表达式,并且可以在包含 WITH 子句的语句中用作
作为表引用

(粗体强调是我的)

© www.soinside.com 2019 - 2024. All rights reserved.