您好我正在尝试解决我的数据库中不存在哪些元素。为了做到这一点,我想比较整数列表(外部脚本的输出)与表中的数据。怎么做这样的事情:
SELECT * FROM (1,1,2,3,5,8,13...) l WHERE l NOT IN (select id from table1);
答案 0 :(得分:3)
最好用left outer join
完成。但是,你的问题是创建常量表:
SELECT *
FROM (select 1 as id union all select 2 union all select 3 union all select 5 union all
select 8 union all select 13 union all select 21 . . .
) ids
where ids.id NOT IN (select id from table1);
如果table1.id
永远是NULL
,这可能会有奇怪的行为。以下更常见的工作原理:
SELECT *
FROM (select 1 as id union all select 2 union all select 3 union all select 5 union all
select 8 union all select 13 union all select 21 . . .
) ids left outer join
table1 t1
on ids.id = t1.id
where t1.id is null;
编辑:
MySQL查询的大小由参数max_packet_size
决定(参见here)。最新版本的限制为1 GB。你应该能够容纳18,000行:
select <n> union all
很容易进入这个限制。天哪,我甚至认为它不会是1兆字节。但是,我会说,通过应用程序传递18,000个ID列表似乎效率低下。如果一个数据库只是从其他数据库中提取数据而不通过应用程序,那就太好了。
答案 1 :(得分:0)
如果您要比较的集合很大,我建议您使用唯一的列myids
创建一个临时表id
,将所有18K值放在那里并运行查询:
select id from myids where myids.id not in (select id from table1);