就您而言,您要删除中story_category
不存在的行category
。
这是您要识别要删除的行的原始查询:
SELECT *
FROM story_category
WHERE category_id NOT IN (
SELECT DISTINCT category.id
FROM category INNER JOIN
story_category ON category_id=category.id
);
NOT IN
与JOIN
原始表的子查询相结合似乎不必要地令人费解。这可以通过not exists
和相关子查询以更直接的方式表示:
select sc.*
from story_category sc
where not exists (select 1 from category c where c.id = sc.category_id);
现在,很容易将其转换为delete
语句:
delete from story_category
where not exists (select 1 from category c where c.id = story_category.category_id);
这个查询器可以在任何MySQL版本以及我所知道的大多数其他数据库中运行。
DB Fiddle上的演示:
-- set-up
create table story_category(category_id int);
create table category (id int);
insert into story_category values (1), (2), (3), (4), (5);
insert into category values (4), (5), (6), (7);
-- your original query to identify offending rows
SELECT *
FROM story_category
WHERE category_id NOT IN (
SELECT DISTINCT category.id
FROM category INNER JOIN
story_category ON category_id=category.id);
| category_id |
| ----------:|
| 1 |
| 2 |
| 3 |
-- a functionally-equivalent, simpler query for this
select sc.*
from story_category sc
where not exists (select 1 from category c where c.id = sc.category_id)
| category_id |
| ----------:|
| 1 |
| 2 |
| 3 |
-- the delete query
delete from story_category
where not exists (select 1 from category c where c.id = story_category.category_id);
-- outcome
select * from story_category;
| category_id |
| ----------:|
| 4 |
| 5 |