我有一个要优化的查询,需要 29 秒才能完成。我曾尝试创建联合加入的视图,但结果更差。
select o.orderno, o.orderdate, c.lastname
from orders o
join (select
`hdb`.`contacts`.`CONTACTID` AS `CONTACTID`,
`hdb`.`contacts`.`LASTNAME` AS `LASTNAME`
from `hdb`.`contacts`
union
select
`sugarcrm`.`contacts`.`id` AS `CONTACTID`,
`sugarcrm`.`contacts`.`last_name` AS `LASTNAME`
from `sugarcrm`.`contacts` ) c on c.CONTACTID = o.CONTACTID
order by orderno desc
limit 0,100000000
在 mysql 慢查询日志下,我得到以下部分:
select
`hdb`.`contacts`.`CONTACTID` AS `CONTACTID`,
`hdb`.`contacts`.`CLIENTID` AS `CLIENTID`,
concat(`hdb`.`contacts`.`FIRSTNAME`,_utf8' ',coalesce(`hdb`.`contacts`.`INITIALS`,_utf8'')) AS `FIRSTNAME`,
`hdb`.`contacts`.`LASTNAME` AS `LASTNAME`,
`hdb`.`contacts`.`PHONE` AS `PHONE`,
`hdb`.`contacts`.`FAX` AS `FAX`,
`hdb`.`contacts`.`DEPARTMENT` AS `DEPARTMENT`,
`hdb`.`contacts`.`TITLE` AS `TITLE`,
`hdb`.`contacts`.`INFO` AS `INFO`,
`hdb`.`contacts`.`SALUTATION` AS `SALUTATION`,
`hdb`.`contacts`.`EMAIL` AS `EMAIL`,
CASE
WHEN `hdb`.`contacts`.`ACTIVE` != 0 THEN 0
ELSE 1
END DELETED,
'paradox' AS `SOURCEDATABASE`
from `hdb`.`contacts`
union
select
`sugarcrm`.`contacts`.`id` AS `CONTACTID`,
`sugarcrm`.`accounts_contacts`.`account_id` AS `CLIENTID`,
`sugarcrm`.`contacts`.`first_name` AS `FIRSTNAME`,
`sugarcrm`.`contacts`.`last_name` AS `LASTNAME`,
`sugarcrm`.`contacts`.`phone_work` AS `PHONE`,
`sugarcrm`.`contacts`.`phone_fax` AS `FAX`,
`sugarcrm`.`contacts`.`department` AS `department`,
`sugarcrm`.`contacts`.`title` AS `title`,
`sugarcrm`.`contacts`.`description` AS `INFO`,
`sugarcrm`.`contacts`.`salutation` AS `salutation`,
`sugarcrm`.`email_addresses`.`email_address` AS `Email`,
`sugarcrm`.`contacts`.`deleted` AS DELETED,
'sugar' AS `SOURCEDATABASE`
from (((`sugarcrm`.`contacts`
left join `sugarcrm`.`email_addr_bean_rel`
on((`sugarcrm`.`contacts`.`id` = `sugarcrm`.`email_addr_bean_rel`.`bean_id`)))
left join `sugarcrm`.`accounts_contacts`
on((`sugarcrm`.`contacts`.`id` = `sugarcrm`.`accounts_contacts`.`contact_id`)))
join `sugarcrm`.`email_addresses`
on((`sugarcrm`.`email_addr_bean_rel`.`email_address_id` = `sugarcrm`.`email_addresses`.`id`)))
但是,如果单独运行,它会运行得很快。使用解释给了我以下信息。
1, PRIMARY, o, ALL, , , , , 6085, Using temporary; Using filesort
1, PRIMARY, <derived2>, ALL, , , , , 18877, Using where
2, DERIVED, contacts, ALL, , , , , 8009,
3, UNION, contacts, ALL, , , , , 10251,
, UNION RESULT, <union2,3>, ALL, , , , , ,