2013-05-10 55 views
2

基本上我試圖從每個url匹配的單詞中獲得總計數。我有這樣的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. 
+4

在整個查詢之前鍵入'EXPLAIN'並將輸出附加到帖子中。 – 2013-05-10 13:10:30

+0

你有什麼指標在你的桌子上?你試過解釋查詢嗎? – GordonM 2013-05-10 13:17:02

+0

您是否只希望那些既包含搜索詞的網址,也包含那些包含*或*搜索詞的網址? – 2013-05-10 13:20:35

回答

3

預彙總:

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') 
+0

工作得很好,並在不到1秒的時間內給出結果。謝謝。 – 2013-05-10 16:28:19

1

使用JOIN,而不是一個子查詢:

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

您最初的查詢運行緩慢在MySQL,因爲MySQL是執行子查詢的每一行結果集。您可以通過做一次彙總,並加入該結果解決這個問題:

select w.url, w.word, w.count, wsum.sumcount 
from wordcoutns w join 
    (select w.url, w.word, SUM(w.count) as sumcount 
     from wordcounts w 
     where w.word in ('search', 'more') 
     group by w.url, w.word 
    ) wsum 
    on wsum.url = w.url and wsum.word = w.word 
where w.word in ('search', 'more') 

其他數據庫支持的一類叫做窗口功能,使這更容易的功能。 MySQL不支持這些。

+1

查詢不起作用... – 2013-05-10 16:26:48