簡體   English   中英

如何在MySql中使用where和group by

[英]How using where and group by for MySql

我的數據庫中有一個表:

CREATE TABLE `yapial` (
  `user_id` int(11) NOT NULL,
  `username` varchar(255) DEFAULT NULL,
  `first_name` varchar(50) DEFAULT NULL,
  `last_name` varchar(50) DEFAULT NULL,
  `gender` varchar(10) DEFAULT NULL,
  `password` varchar(50) DEFAULT NULL,
  `status` tinyint(10) DEFAULT NULL,
  `date` datetime NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

狀態日期列索引。 我運行sql代碼:

select status, count(*) from user_details group by status

並且成功運行0.34ms。 但我想添加日期限制=>

select date, status, count(*) from user_details 
where date between '2017-01-25 18:13:50' and '2017-01-29 18:13:50'
group by status

成功運行6.52s。 時間限制太高了。 我想減少時間。 我應該如何改進?

需要0.34ms的查詢可能是從MySQL查詢緩存中獲得的結果。 查詢不太可能那么快。

我認為最好的優化是你有一個雙列索引。 有兩種可能性:

alter table user_details
  add key (status, date),
  add key (date, status);

如果使用第一個索引,它將執行索引掃描,但它將避免臨時表:

explain select sql_no_cache date, status, count(*) 
  from user_details use index (status) 
  where date between '2017-01-25 18:13:50' and '2017-01-29 18:13:50'
  group by status\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: user_details
   partitions: NULL
         type: index
possible_keys: date,status
          key: status
      key_len: 7
          ref: NULL
         rows: 3
     filtered: 33.33
        Extra: Using where; Using index

如果使用第二個索引,它將使用索引進行范圍查找,按日期范圍匹配行,但它將導致臨時表。

root@localhost [test] > explain select sql_no_cache date, status, count(*) 
    from user_details use index (date) 
    where date between '2017-01-25 18:13:50' and '2017-01-29 18:13:50' 
    group by status\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: user_details
   partitions: NULL
         type: range
possible_keys: date,status
          key: date
      key_len: 5
          ref: NULL
         rows: 1
     filtered: 100.00
        Extra: Using where; Using index; Using temporary; Using filesort

哪個索引最好取決於與條件匹配的行數。

暫無
暫無

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

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