我有一些查询速度问题,它显示了我的数据库中的用户列表。我想显示具有交通信息的用户列表以及与用户一起工作的最后一位员工。
数据库看起来像这样:
用户表(包含用户信息):
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ip` tinytext NOT NULL,
`name` varchar(64) NOT NULL,
... some other fields
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`),
KEY `ip` (`ip`(15)) USING BTREE,
)
users_trf 表(包含有关用户流量的信息;uid - users 表中的用户 ID):
CREATE TABLE `users_trf` (
`uid` int(11) unsigned NOT NULL,
`uip` varchar(15) CHARACTER SET latin1 COLLATE latin1_bin NOT NULL,
`in` bigint(20) NOT NULL DEFAULT '0',
`out` bigint(20) NOT NULL DEFAULT '0',
`test` tinyint(4) NOT NULL,
UNIQUE KEY `uid` (`uid`),
KEY `test` (`test`)
)
所有员工名单的员工:
CREATE TABLE `employees` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`full_name` varchar(16) NOT NULL,
PRIMARY KEY (`id`)
)
和日志表,我在其中存储有关员工对客户端所做的工作的数据(uid - 来自用户表的客户端 ID,mid - 来自员工表的员工 ID):
CREATE TABLE `employees_log` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`uid` int(10) unsigned NOT NULL,
`mid` int(10) unsigned NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`note` text NOT NULL,
PRIMARY KEY (`id`)
)
我的查询:
SELECT SQL_CALC_FOUND_ROWS *
FROM users u
LEFT JOIN users_trf t ON u.id = t.uid
LEFT JOIN (
SELECT e2.full_name, e1.uid, e1.mid AS moid
FROM employees_log e1
LEFT JOIN employees e2 ON e1.mid = e2.id
WHERE NOT
EXISTS (
SELECT *
FROM employees_log e3
WHERE e1.uid = e3.uid
AND e1.id < e3.id
)
) e ON e.uid = u.id
LIMIT 0 , 50
它工作得非常慢,我认为这是这个子查询的原因(我正在尝试选择最后一位与客户合作的员工):
SELECT e2.full_name, e1.uid, e1.mid AS moid
FROM employees_log e1
LEFT JOIN employees e2 ON e1.mid = e2.id
WHERE NOT
EXISTS (
SELECT *
FROM employees_log e3
WHERE e1.uid = e3.uid
AND e1.id < e3.id
)
是否可以加快我的查询速度?
UPD:我添加索引ALTER TABLE employees_log ADD INDEX ( uid, id );
和查询变得快了 2 倍,但我可以让它更快吗?
+----+--------------------+------------+--------+---------------+---------+---------+-------------+-------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------------+------------+--------+---------------+---------+---------+-------------+-------+--------------------------+
| 1 | PRIMARY | u | ALL | NULL | NULL | NULL | NULL | 12029 | |
| 1 | PRIMARY | t | eq_ref | uid | uid | 4 | bill.u.id | 1 | |
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 2239 | |
| 2 | DERIVED | e1 | ALL | NULL | NULL | NULL | NULL | 2288 | Using where |
| 2 | DERIVED | e2 | eq_ref | PRIMARY | PRIMARY | 4 | bill.e1.mid | 1 | |
| 3 | DEPENDENT SUBQUERY | e3 | ref | PRIMARY,uid | uid | 4 | bill.e1.uid | 1 | Using where; Using index |
+----+--------------------+------------+--------+---------------+---------+---------+-------------+-------+--------------------------+