mysql查询需要4分钟才能执行

时间:2016-07-27 12:14:24

标签: mysql

表1。

CREATE TABLE `admin_users` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`branch_id` int(11) DEFAULT '0',
`landingpage` int(11) DEFAULT '8',
`user_role_id` int(11) DEFAULT '0',
`user_parent_role` int(11) DEFAULT '0',
`bank_branch_id` int(11) DEFAULT '0',
`status` enum('1','0') COLLATE utf8_unicode_ci DEFAULT '1',
`firstname` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`lastname` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`), KEY `user_role_id` (`user_role_id`)
) ENGINE=InnoDB AUTO_INCREMENT=281 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC COMMENT='الموظفين';

表2。

CREATE TABLE `application_activity` (
`activityid` bigint(11) NOT NULL AUTO_INCREMENT,
`dataid` text,
`datatable` varchar(255) DEFAULT NULL,
`userid` int(11) DEFAULT '0',
`activitytype` char(1) DEFAULT 'I',
`activitytime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`activityip` varchar(15) DEFAULT NULL,
`activitydevice` text,
PRIMARY KEY (`activityid`)) ENGINE=MyISAM AUTO_INCREMENT=152862 DEFAULT CHARSET=utf8 COMMENT='نشاط التطبيق';

查询我正在执行。

SELECT admin_users.`firstname`,admin_users.`lastname`,admin_users.`id`, branches.`branch_name`,
            (SELECT COUNT(activityid) FROM application_activity WHERE userid=admin_users.`id`) AS cnt,
            (SELECT activitytype FROM application_activity WHERE userid=admin_users.`id` ORDER BY activityid DESC LIMIT 0,1) AS activitytype,
            (SELECT datatable FROM application_activity WHERE userid=admin_users.`id` ORDER BY activityid DESC LIMIT 0,1) AS datatable,
            (SELECT activitytime FROM application_activity WHERE userid=admin_users.`id` ORDER BY activityid DESC LIMIT 0,1) AS activitytime
            FROM admin_users
            JOIN branches ON branches.`branch_id`=admin_users.`branch_id`
            HAVING cnt > 0
            ORDER BY cnt DESC

表1有100个用户记录,表2有超过100k的应用程序活动记录。

当我执行查询时,需要4分钟才能给出结果。

1 个答案:

答案 0 :(得分:0)

对于此查询:

这是您的查询:

SELECT au.`firstname`, au.`lastname`, au.`id`, b.`branch_name`,
       (SELECT COUNT(*) FROM application_activity aa WHERE aa.userid = admin_users.`id`) AS cnt,
            (SELECT aa.activitytype FROM application_activity aa WHERE aa.userid = au.`id` ORDER BY aa.activityid DESC LIMIT 0,1) AS activitytype,
            (SELECT aa.datatable FROM application_activity aa WHERE aa.userid = au.`id` ORDER BY aa.activityid DESC LIMIT 0,1) AS datatable,
            (SELECT aa.activitytime FROM application_activity aa WHERE aa.userid = au.id` ORDER BY aa.activityid DESC LIMIT 0,1) AS activitytime
FROM admin_users au JOIN
     branches b
     ON b.`branch_id` = au.`branch_id`
HAVING cnt > 0
ORDER BY cnt DESC;

您需要适当的索引。一个在branches(branch_id)上 - 但你可能已经有了这个。

第二个是application_activity(userid, activityid)

我强烈建议当相关子查询中的所有列都使用表别名进行限定时。