2017-01-25 21 views
1

我有一個表在我的數據庫:如何使用WHERE和GROUP BY對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

以0.34ms爲單位的查詢可能從MySQL query cache得到結果。查詢速度不太快。

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

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 

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

[email protected] [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 

哪個索引最好取決於有多少行匹配條件。

+0

當然這種方法更多的性能。我嘗試併成功運行2.5s。 – user6483202