我有下表:
我需要一个基于以下规则返回结果的查询:
假设我的表名为numbers_table
并且假设表格可能非常大,那么应该在mysql中运行的适当查询是什么?
到目前为止我做了什么:
SELECT nr1,nr2,nr3,nr4,nr5,nr6 FROM numbers where
nr1 in (2, 3, 5, 7, 11, 13, 23, 29, 31, 37, 41, 43, 47) or
nr2 in (2, 3, 5, 7, 11, 13, 23, 29, 31, 37, 41, 43, 47) or
nr3 in (2, 3, 5, 7, 11, 13, 23, 29, 31, 37, 41, 43, 47) or
nr4 in (2, 3, 5, 7, 11, 13, 23, 29, 31, 37, 41, 43, 47) or
nr5 in (2, 3, 5, 7, 11, 13, 23, 29, 31, 37, 41, 43, 47) or
nr6 in (2, 3, 5, 7, 11, 13, 23, 29, 31, 37, 41, 43, 47);
我可以优化上述解决方案吗?
答案 0 :(得分:1)
您可以做的最好的事情是为主要数字Pnumbers(n int)
创建一个表格。你可以很容易地找到所有这些数字或者自己生成数字(https://sqlserverfast.com/blog/hugo/2006/09/the-prime-number-challenge-great-waste-of-time/)。它不是那么大:第一个1,000,000数字中大约80,000。在nr
列上建立索引对您来说效果很好。然后你可以写下面的选择:
select * from tableName t
left join Pnumbers p1 on t.nr1 = p1.n
left join Pnumbers p2 on t.nr2 = p2.n
....
left join Pnumbers p6 on t.nr6 = p6.n
where p1.n is not null or p2.n is not null or ... or p6.n is not null