我有MySQL数据库:
CREATE TABLE IF NOT EXISTS `tableexample` (
`id` int(11) NOT NULL auto_increment,
`val0` tinyint(1) NOT NULL,
`val1` tinyint(1) NOT NULL,
`val2` tinyint(1) NOT NULL,
`val3` tinyint(1) NOT NULL,
`val4` tinyint(1) NOT NULL,
`val5` tinyint(1) NOT NULL,
.................
`val1996` tinyint(1) NOT NULL,
`val1997` tinyint(1) NOT NULL,
`val1998` tinyint(1) NOT NULL,
`val1999` tinyint(1) NOT NULL,
UNIQUE KEY `id` (`id`),
) ENGINE=MEMORY ;
此查询最多可以包含500个字段:
SELECT
( ABS(`val1`-12)
+ ABS(`val22`-22)
+ ABS(`val23`-3)
+ ABS(`val45`-87)
+ ABS(`val76`-23)
........
+ ABS(`val1324`-7)
+ ABS(`val1576`-29)
) as valcal,
id
FROM `tableexample`
ORDER BY valcal ASC
LIMIT 5
此ABS
的数字对于每个查询(12,22,3,87,23,7,29,...)都是唯一的,并且可以在0-99范围内。
我做了一些测试:
for 1000 records the sql run in 0.024 seconds
for 10000 records the sql run in 0.231 seconds
for 50000 records the sql run in 1.123 seconds
for 100000 records the sql run in 2.179 seconds
for 200000 records the sql run in 4.316 seconds
for 300000 records the sql run in 6.451 seconds
您是否有任何优化提示,因为数据库中有大约300,000条记录?
答案 0 :(得分:0)
此查询始终必须运行所有300,000条记录,并对每条记录执行500次计算。大概每秒进行23M的计算,这也不错。优化这一点的唯一方法是更好的硬件,但即便如此也很难。
添加索引无济于事。它可以帮助的唯一方法是完全重新考虑您的结构或逻辑。