删除不起作用:
DELETE FROM categories c
RIGHT JOIN product_categories pg
ON c.id = pg.category_id
WHERE c.id IS NULL
GROUP BY pg.category_id
当使用select时,它确实有效:
SELECT pg.category_id as pg_id
FROM categories c
RIGHT JOIN product_categories pg
ON c.id = pg.category_id
WHERE c.id IS NULL
GROUP BY pg.category_id
我使用select来测试它,select在这种情况下使用pg_id数组给出正确的结果。
我删除了什么?
答案 0 :(得分:1)
改为使用相关查询。
DELETE
FROM categories C
WHERE not exists (SELECT *
FROM product_categories PC
WHERE PC.category_ID = C.ID)
基本上删除product_Category中尚未使用的所有类别。
我的经验法则是,如果我不需要表格中的数据,请不要将其包含在加入/来自中;请注意,这不是一个严格的快速规则。如果您将其用作过滤器,则它属于where或having子句。
答案 1 :(得分:0)
有效且传统的SELECT查询的示例可能如下...
SELECT DISTINCT pg.category_id pg_id
FROM product_categories pg
LEFT
JOIN categories c
ON c.id = pg.category_id
WHERE c.id IS NULL;
相应的DELETE查询可能如下所示:
DELETE pg
FROM product_categories pg
LEFT
JOIN categories c
ON c.id = pg.category_id
WHERE c.id IS NULL;
答案 2 :(得分:0)
我终于有时间弄清楚原始代码中的错误,以及如何删除我想要的内容。
这很受@Strawberry的启发:
选择强>
CarouselPage
删除强>
Navigation.PushAsync()
选择的结果是:
SELECT DISTINCT pg.category_id pg_id, c.id c_id
FROM categories c
LEFT
JOIN product_categories pg
ON c.id = pg.category_id
WHERE pg.category_id IS NULL;
如果DELETE c
FROM categories c
LEFT
JOIN product_categories pg
ON c.id = pg.category_id
WHERE pg.category_id IS NULL;
为空,则会在Array
(
[0] => stdClass Object
(
[pg_id] =>
[c_id] => 2
)
)
中删除pg_id
c_id
2
所在的行。
答案 3 :(得分:-1)
你不能在UPDATE,DELETE中拥有GROUP BY。如果您的查询确实需要GROUP BY,您可以将它放在像这样的子查询
中DELETE c
FROM categories AS c
INNER JOIN (
SELECT pg.category_id
FROM categories c
RIGHT JOIN product_categories pg
ON c.id = pg.category_id
WHERE c.id IS NULL
GROUP BY pg.category_id) AS t ON c.category_id = t.category_id
已更新:
关于您的查询,这没有意义。您想要删除类别表
中未退出的记录