我有一张审计表。我使用这个查询来获取当前没有登录的用户。但是,这个查询在过去几天需要很长时间。在从慢查询日志分析时,检查的行数太长。
当天表中的总行数为6032194
(
select count(*) from audit where audit.created_time
between UNIX_TIMESTAMP(CURRENT_DATE() - INTERVAL 3 DAY) * 1000
AND UNIX_TIMESTAMP(CURRENT_DATE()-INTERVAL 2 day) * 1000
)。
询问
select count(user_id) from audit where audit.created_time
between UNIX_TIMESTAMP(CURRENT_DATE() - INTERVAL 3 DAY) * 1000 AND
UNIX_TIMESTAMP(CURRENT_DATE()-INTERVAL 2 day) * 1000
and operation in ('s','g','y','fb');
解释输出
id: 1
select_type: SIMPLE
table: audit
type: range
possible_keys: IAMAccountAudit_CTndx
key: IAMAccountAudit_CTndx
key_len: 9
ref: NULL
rows: 16434866
Extra: Using where
它作为范围查询执行。但它检查86158436
行。
慢查询日志:
# Time: 130216 1:09:21
# User@Host: root[root] @ [bharathik]
# Query_time: 1853.751416 Lock_time: 0.000101 Rows_sent: 1 Rows_examined: 86158436
SET timestamp=1361005761;
SELECT UNIX_TIMESTAMP(CURRENT_DATE() - INTERVAL 1 DAY) * 1000, 'SIGNIN', 0, count(distinct(zuid)) as SIGN_IN_COUNT from audit where audit.CREATED_TIME BETWEEN
UNIX_TIMESTAMP(CURRENT_DATE() - INTERVAL 3 DAY) * 1000 AND
UNIX_TIMESTAMP(CURRENT_DATE()-INTERVAL 2 day) * 1000
创建表
+-----------------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------------------+--------------+------+-----+---------+-------+
| auto_id | bigint(19) | NO | PRI | 0 | |
| user_id | varchar(100) | YES | MUL | NULL | |
| service | varchar(100) | YES | | NULL | |
| name | varchar(100) | YES | | NULL | |
| operation | varchar(15) | YES | | NULL | |
| ipaddress | varchar(50) | YES | | NULL | |
| referrer | varchar(250) | YES | | NULL | |
| user_agent | varchar(250) | YES | | NULL | |
| created_time | bigint(19) | YES | MUL | NULL | |
+-----------------------+--------------+------+-----+---------+-------+