簡體   English   中英

mysql在連接查詢的小表上性能較差

[英]mysql slow performance on a small table with join query

當我執行以下查詢時,我有幾個表連接在一起:

SELECT article.year, authors.last_name, count(DISTINCT article.id) as count FROM
article LEFT JOIN authors ON article.id = authors.id WHERE authors.last_name =
'bloggs' GROUP BY article.year

出於某種原因,這需要6到7秒的時間才能返回結果,這對我來說似乎要慢得多,因為它必須處理的行數相對較少。 我在這里做錯了嗎?

如果我在查詢上運行EXPLAIN,我會得到以下內容:

select_type    table    type   possible_keys  key    key_len    ref    rows    extra
=====================================================================================
simple         article  all    null           null    null      null   762     using temporary; using filesort
simple         authors  all    null           null    null      null   5061    using where; using join buffer

兩個表都是InnoDB。 我從我的本地機器運行這個相當低的規格(windows xp,1 ghz,1gb ram),但即便如此,我還以為這會更快。 如果我在表中加載更多行,則開始需要幾分鍾而不是幾秒鍾。

有什么想法嗎?

表結構如下:

Article:

field    type       null    key    default    extra
=======================================================
id       int        yes            null
year     char(20)   yes            null
volume   char(20)   yes            null
issue    char(20)   yes            null
title    text       yes            null

Authors:

field      type       null    key    default    extra
=======================================================
id         int        yes            null
last_name  char(100)  yes            null
initials   char(10)   yes            null

嘗試在authors.last_nameauthors.id列上添加索引。

但是,你確定你的查詢沒問題嗎? 不應該看起來像:

SELECT article.year, authors.last_name, count(DISTINCT article.id) as count FROM
article LEFT JOIN authors ON article.author_id = authors.id WHERE authors.last_name =
'bloggs' GROUP BY article.year

如果是這樣,則需要在articles.author_id上建立索引 - 盡管不是針對此查詢,而是作為一般的最佳實踐

正如都鐸所說,添加索引。 您還可以通過提取組。

SELECT * FROM (SELECT article.year, authors.last_name, count(DISTINCT article.id) as count FROM
article LEFT JOIN authors ON article.author_id = authors.id WHERE authors.last_name =
'bloggs') GROUP BY article.year

這樣做是首先通過連接獲取,並在集合中應用聚合函數。

explain看哪里有改善的地方。

建議字體:

http://kccoder.com/mysql/join-group-by-performance/

暫無
暫無

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

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