MySQL 只会返回存在的行。要返回丢失的行,您必须有两个表。
第一个表可以是临时的(特定于会话/连接),以便多个实例可以同时运行。
create temporary table tmpMustExist (text id);
insert into tmpMustExist select "ida";
insert into tmpMustExist select "idb";
-- etc
select a.id from tmpMustExist as a
left join table b on b.id=a.id
where b.id is null; -- returns results from a table that are missing from b table.
这可以通过单个 sql 查询实现吗?
嗯,是的。让我按照自己的方式进行操作,首先使用 union all 组合 select 语句。
create temporary table tmpMustExist (text id);
insert into tmpMustExist select "ida" union all select "idb" union all select "etc...";
select a.id from tmpMustExist as a left join table as b on b.id=a.id where b.id is null;
请注意,我使用 union all,它比 union 快一点,因为它跳过了重复数据删除。
您可以使用create table...select。我经常这样做并且非常喜欢它。 (这也是复制表的好方法,但会删除索引。)
create temporary table tmpMustExist as select "ida" union all select "idb" union all select "etc...";
select a.id from tmpMustExist as a left join table as b on b.id=a.id where b.id is null;
最后,您可以使用所谓的“派生”表将整个内容整合到一个单一的、可移植的 select 语句中。
select a.id from (select "ida" union all select "idb" union all select "etc...") as a left join table as b on b.id=a.id where b.id is null;
注意:as 关键字是可选的,但阐明了我对 a 和 b 所做的事情。我只是创建要在join 和select 字段列表中使用的短名称