我尝试删除所有type_name以D开头的商品
假设我想从牙科、美食、飞镖游戏类型中删除商品。 因此,我检查 type 是否在列表 d_goods_ids 中(type 是 good_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;
在这种情况下,两种变体不应该发挥相同的作用吗?
您可以在子查询中引用 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
子句的语句中用作作为表引用。
(粗体强调是我的)