簡體   English   中英

sql查詢查找質數

[英]sql query for finding prime numbers

假設我在一個表中有1到100的數字。 我需要編寫查詢以從該表中提取所有素數。 如何在不使用任何類型的過程或循環的情況下,通過一個非常簡單的基本查詢來實現此目標。

選擇MyISAM是有原因的。 我將在評論中解釋。 主要是為了確保在自我插入過程中不會出現innodb間隙(從而丟棄id)。 不要過多地研究模式部分。 我只需要生成一個表1到100。

對於MyISAM,它不會受到INNODB間隙反常ref1 ref2的影響,並且它保證在自動插入和INNODB間隙范圍內不會發生1到100的間隙。

無論如何,如果您提供了實際的表格,我就無需提及。 或者, 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; 

結果

+----+
| id |
+----+
|  2 |
|  3 |
|  5 |
|  7 |
| 11 |
| 13 |
| 17 |
| 19 |
| 23 |
| 29 |
| 31 |
| 37 |
| 41 |
| 43 |
| 47 |
| 53 |
| 59 |
| 61 |
| 67 |
| 71 |
| 73 |
| 79 |
| 83 |
| 89 |
| 97 |
+----+
25 rows in set (0.00 sec)

注意,上面的ref2是誇張的“快速創建4.7M行表”,如果不這樣做的話,肯定會創建INNODB id間隙。 這只是該引擎的已知事實。

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM