使用多个连接和交叉连接优化查询时间

时间:2015-06-15 11:08:40

标签: mysql

我有三个具有给定结构的表

cron_mails  --- it contains all mails fired for each job
____________________________________
| id | user_id | vehicle_id | date |
_____________________________________________________
cron_jobs  --- it contains jobs for new vehicle added by users
|  id  | user_id (sender_id)   | vehicle_id  | date  |
_____________________________________________________

 users
| id    | email | email_option | status |
_________________________________________


Select u.id as reciever_id , u.email as user_email, cj.user_id as sender_id , 
GROUP_CONCAT(cj.user_id) as sender_id , GROUP_CONCAT(cj.vechile_id) as vechile_id
FROM users as u 
CROSS JOIN cron_jobs as cj
LEFT JOIN cron_mails as cm ON cj.vechile_id = cm.vechile_id 
                          AND cm.type = 1 AND cm.user_id = u.id
WHERE cm.user_id IS NULL 
and u.id != cj.user_id 
and u.status = 1 
and u.user_type = 3 
AND NOW() > cj.date 
AND u.email_option = 1
ORDER BY cj.date

此查询需要花费大量时间执行。

还有其他方法可以执行相同的查询吗?

必填结果是查找所有不在corn_mails表中且具有相同车辆ID但在cron_job

中具有相同车辆ID的用户
  • 用户位于“用户”表格
  • 用户添加一些作业,并使用vehicle_id
  • 在cron_jobs表中记录他们的作业
  • 现在我们需要从users表中找到排除用户添加的作业的用户,并排除cron_mails表中具有相同vehicle_id的用户

解释查询的结果是:

 id     select_type     table   type    possible_keys   key     key_len     ref     rows    Extra   
 1      SIMPLE           cj     ALL     NULL            NULL    NULL    NULL        138     Using where; Using temporary; Using filesort
 1      SIMPLE            u     ALL     NULL            NULL    NULL    NULL        983     Using where; Using join buffer
 1      SIMPLE           cm     ALL     NULL            NULL    NULL    NULL        41872   Using where; Not exists

0 个答案:

没有答案