bin
发布于

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

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

假设想从牙科、美食darts_game类型中删除商品。 因此,检查该类型是否在列表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;

在这种情况下,两种变体不是应该工作得一样吗?

浏览 (14)
点赞
收藏
1条评论
Klustron小助手
试试这种? WITH d_goods_ids AS ( SELECT good_type_id FROM GoodTypes WHERE GoodTypes.good_type_name LIKE "d%" ) DELETE Goods FROM Goods JOIN d_goods_ids ON d_goods_ids.good_type_id = Goods.type;
点赞
评论