就问题而言,您希望删除story_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原始表的子查询组合在一起似乎不太复杂。这可以用不存在和相关子查询以更直接的方式表示:
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);
这个quer可以在任何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 |