[英]Find values missing in a column from a set (mysql)
我正在使用mysql。
我有一个具有列ID的表。
假设我有一组输入ID。 我想知道表格中缺少哪些所有ID。
如果集合为“ ida”,“ idb”,“ idc”,并且表仅包含“ idb”,则返回值应为“ ida”,“ idc”。
单个sql查询可能吗? 如果没有,执行此操作的最有效方法是什么。
请注意,我不允许使用存储过程。
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
并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
字段列表中使用
//you can pass each set string to query
//pro-grammatically you can put quoted string
//columns must be utf8 collation
select * from
(SELECT 'ida' as col
union
SELECT 'idb' as col
union
SELECT 'idc' as col ) as setresult where col not in (SELECT value FROM `tbl`)
有个把戏。 您可以创建具有期望值的表,也可以对每个值使用多项选择的并集。
然后,您需要找到标准具中的所有值,而不是测试表中的所有值。
CREATE TABLE IF NOT EXISTS `single` (
`id` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `single` (`id`) VALUES
('idb');
SELECT a.id FROM (
SELECT 'ida' as id
UNION
SELECT 'idb' as id
UNION
SELECT 'idc' AS id
) a WHERE a.id NOT IN (SELECT id FROM single)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.