我已经阅读了很多关于这里的回复,但没有什么能够像我想的那样工作。我目前有一个包含2个子查询的工作查询,问题是需要大约10秒钟才能执行。我想知道是否有任何方法可以使这个更快,也许加入。我似乎无法把我的脑袋从盒子里拿出来,请让我知道你的想法。加入最近的日期
这里是工作的查询:
Select concat(a.emp_firstname, ' ', a.emp_lastname) as names
, if(if (a.emp_gender = 1, 'Male', a.emp_gender)=2, 'Female',
if (a.emp_gender = 1, 'Male', a.emp_gender)) as emp_gender
, c.name
, a.emp_work_telephone
, a.emp_hm_telephone, a.emp_work_email
, a.custom7, a.employee_id
, a.city_code, a.provin_code, d.name as status,
(SELECT cast(concat(DATE_FORMAT(e.app_datetime, '%H:%i'), ' ', e.app_facility) as char(100))
FROM li_appointments.li_appointments as e where e.terp_id = a.employee_id
and e.app_datetime <= str_to_date('06/26/13 at 3:20 PM', '%m/%d/%Y at %h:%i %p')
and date(e.app_datetime) = date(str_to_date('06/26/13 at 3:20 PM', '%m/%d/%Y at %h:%i %p'))
order by e.app_datetime desc limit 1) as prevapp,
(SELECT cast(concat(DATE_FORMAT(e.app_datetime, '%H:%i'), ' ', e.app_facility) as char(100))
FROM li_appointments.li_appointments as e
where e.terp_id = a.employee_id
and e.app_datetime > str_to_date('06/26/13 at 3:20 PM', '%m/%d/%Y at %h:%i %p')
and date(e.app_datetime) = date(str_to_date('06/26/13 at 3:20 PM', '%m/%d/%Y at %h:%i %p'))
order by e.app_datetime desc limit 1) as nextapp
from hs_hr_employee as a
Join hs_hr_emp_skill as b on a.emp_number = b.emp_number
Join ohrm_skill as c on b.skill_id = c.id
Join orangehrm_li.ohrm_employment_status as d on a.emp_status = d.id
where c.name like '%Arabic%'
and d.name = 'Active' order by rand();
EXPLAIN
结果:
+----+--------------------+-------+--------+---------------------+------------+---------+---------------------------+-------+----------------------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+--------------------+-------+--------+---------------------+------------+---------+---------------------------+-------+----------------------------------------------+ | 1 | PRIMARY | d | ALL | PRIMARY | | | | 10 | Using where; Using temporary; Using filesort | | 1 | PRIMARY | a | ref | PRIMARY,emp_status | emp_status | 5 | orangehrm_li.d.id | 48 | Using where | | 1 | PRIMARY | b | ref | emp_number,skill_id | emp_number | 4 | orangehrm_li.a.emp_number | 1 | | | 1 | PRIMARY | c | eq_ref | PRIMARY | PRIMARY | 4 | orangehrm_li.b.skill_id | 1 | Using where | | 3 | DEPENDENT SUBQUERY | e | ALL | | | | | 28165 | Using where; Using filesort | | 2 | DEPENDENT SUBQUERY | e | ALL | | | | | 28165 | Using where; Using filesort | +----+--------------------+-------+--------+---------------------+------------+---------+---------------------------+-------+----------------------------------------------+
的索引查找深一点,请发表'EXPLAIN SELECT(yourquery)'的输出。 – Bjoern
如果您通过rand()移除您的订单,会发生什么?虽然我可以看到它可能是有用的,但如果您的记录选择很大,可能会使数据库陷入困境。 –
乔,结果通常在20-30行左右。在我的测试中,rand()似乎不成问题。当我删除子查询时,总持续时间小于0.02秒。 –