假设我在表格中有1到100的数字。 我需要编写一个查询来从该表中提取所有素数。如何在不使用任何过程或循环的情况下使用非常基本和简单的查询来实现此目的。
答案 0 :(得分:1)
至于MyISAM,它不会受到INNODB间隙异常ref1 ref2的影响,并且它保证在自插入和INNODB间隙范围内不会出现1到100的间隙。
无论如何,如果您提供了实际的表格,我就不需要提及。或者ping()
可以在数据加载后更改引擎。
ALTER TABLE
create table nums
( id int auto_increment primary key,
thing char(1) null
)ENGINE=MyISAM;
insert nums(thing) values(null),(null),(null),(null),(null),(null),(null);
insert nums(thing) select thing from nums;
insert nums(thing) select thing from nums;
insert nums(thing) select thing from nums;
insert nums(thing) select thing from nums;
select count(*) from nums; -- 112
delete from nums where id>100;
select min(id),max(id),count(*) from nums;
-- 1 100 100
select id from nums where id>1 and id not in
( select distinct n2id
from
( select n1.id as n1id, n2.id as n2id
from nums n1
cross join nums n2
where n1.id<(n2.id) and n1.id>1 and (n2.id MOD n1.id = 0)
) xDerived
)
order by id;
注意,上面的 ref2 是一个夸张的&#34;快速创建一个4.7M的行表&#34;如果不这样做,那肯定会创造INNODB id差距。这个引擎只是一个众所周知的事实。
答案 1 :(得分:0)
SET @potential_prime = 1;
SET @divisor = 1;
SELECT GROUP_CONCAT(POTENTIAL_PRIME SEPARATOR ',') FROM
(SELECT @potential_prime := @potential_prime + 1 AS POTENTIAL_PRIME FROM
information_schema.tables t1,
information_schema.tables t2
LIMIT 1000) list_of_potential_primes
WHERE NOT EXISTS(
SELECT * FROM
(SELECT @divisor := @divisor + 1 AS DIVISOR FROM
information_schema.tables t4,
information_schema.tables t5
LIMIT 1000) list_of_divisors
WHERE MOD(POTENTIAL_PRIME, DIVISOR) = 0 AND POTENTIAL_PRIME <> DIVISOR);