簡體   English   中英

MySQL GROUP BY與不必要地使用Temporary嗎?

[英]MySQL GROUP BY with Using Temporary unnecessarily?

我正在嘗試優化查詢。 使用EXPLAIN告訴我它是Using temporary 考慮到表的大小(20m +條記錄),這確實效率很低。 在查看MySQL文檔的內部臨時表時,我看不到任何暗示查詢中需要臨時表的內容。 我還嘗試將ORDER BY設置為與GROUP BY相同,但仍然說“使用臨時”,並且查詢需要永遠運行。 我正在使用MySQL 5.7。

有沒有一種方法可以避免對此查詢使用臨時表:

SELECT url,count(*) as sum 
FROM `digital_pageviews` as `dp` 
WHERE `publisher_uuid` = '8b83120e-3e19-4c34-8556-7b710bd7b812' 
GROUP BY url 
ORDER BY NULL;

這是我的表架構:

create table digital_pageviews
(
  id             int unsigned auto_increment
    primary key,
  visitor_uuid   char(36)            null,
  publisher_uuid char(36) default '' not null,
  property_uuid  char(36)            null,
  ip_address     char(15)            not null,
  referrer       text                null,
  url_delete     text                null,
  url            varchar(255)        null,
  url_tmp        varchar(255)        null,
  meta           text                null,
  date_created   timestamp           not null,
  date_updated   timestamp           null
)
  collate = utf8_unicode_ci;

create index digital_pageviews_url_index
  on digital_pageviews (url);

create index ndx_date_created
  on digital_pageviews (date_created);

create index ndx_property_uuid
  on digital_pageviews (property_uuid);

create index ndx_publisher_uuid
  on digital_pageviews (publisher_uuid);

create index ndx_visitor_uuid_page
  on digital_pageviews (visitor_uuid);

之所以需要一個臨時表,是因為它既不能按publisher_uuid進行過濾,也不能對沒有索引的列進行排序。 第一步是按publisher_uuid進行過濾,因此它將使用publisher_uuid上的索引。

但是,接下來它必須對記錄進行分組和排序,這將需要一個臨時表,因為它不能使用執行此操作的索引。 之所以不能使用索引,是因為它已經使用了publisher_uuid ,但未在url字段上建立索引,因此無法對您依據的字段進行分組。

要過濾哪里publisher_uuid = '8b83120e-3e19-4c34-8556-7b710bd7b812' ,按url分組和按url排序,請按以下順序創建包含這些字段的索引:

  • Publisher_uuid
  • 網址
create index ndx_publisher_uuid
  on digital_pageviews (publisher_uuid, url);

暫無
暫無

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

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