java - 优化sql查询,即使是小数据也太慢

标签 java mysql sql

基本上,我试图从与每个网址匹配的单词中获取总计数。我有这个 sql 查询:

select w.url, w.word, w.count, (
select sum(w2.count)
from wordcounts w2 where w2.url = w.url and w2.word in ('search', 'more')
) as totalcount
from wordcounts w
where w.word in ('search', 'more')

我正在使用此查询来获取这种结果:

URL                              |  word  | count | Total Count

http://haacked.com/              | more   | 61    | 62
http://haacked.com/              | search | 1     | 62
http://feeds.haacked.com/haacked | more   | 58    | 59
http://feeds.haacked.com/haacked | search | 1     | 59
http://www.asp.net/privacy       | more   | 7     | 13
http://www.asp.net/privacy       | search | 6     | 13

我原来的表结构是

ID | URL  |  word  | count

但问题是,这个小查询花费了太多时间。在几千行上运行上述查询需要 7 秒以上。如何优化这个查询?

我从另一个网站获得了这个语法,但它给出了错误。

select id, url, word, count, 
sum(count) over(partition by url) as count_sum
from wordcounts where word in ('search', 'more') order by url

Error code 1064, SQL state 42000: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(partition by url) as count_sum
from wordcounts where word in ('search', 'more')' at line 2
Line 1, column 1

Execution finished after 0 s, 1 error(s) occurred.

最佳答案

预聚合:

select w.url, w.word, w.`count`, w3.totalcount
from wordcounts w
join (
     select w2.url, sum(w2.`count`) totalcount
     from wordcounts w2
     where w2.word in ('search', 'more')
     group by w2.url) w3 on w3.url = w.url
where w.word in ('search', 'more')

关于java - 优化sql查询,即使是小数据也太慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16483054/

相关文章:

java - 如何获取字符串数组并将它们进一步分成对象?

PHP 从数据库导出 CSV 表

mysql - MySQL中检查where子句限制的两个表时如何仅从一张表的列中选择数据

sql - PLSQL、SQL*PLUS 获取当前用户名?

java - Apache HttpClientBuilder 产生 ClassNotFoundException : org. apache.http.config.Lookup

java - 将 key 对导入现有 key 对文件

java - 在java中检查4个Arraylists不包含相同值的最简单方法

mysql - Rails 和数据库 : How do you do it nicely when things get messy?

mysql - InnoDB 是否缓存不存在的键?

sql - MS SQL 更新锁定