我有这样的查询:
SELECT *,
CASE
WHEN text LIKE 'harv' THEN 1
WHEN text LIKE 'harv%' THEN 2
WHEN text LIKE '%harv%' THEN 3
END AS priority
FROM
( SELECT b.bschool_name AS `text`,
'bschool' AS `type`,
b.slug AS `id`,
n.neighbourhood AS 'params'
FROM bschool b
LEFT JOIN bschool_addresses ba ON (b.id=ba.bschool_id)
LEFT JOIN neighbourhoods n ON (ba.neighbourhood_id=n.id)
WHERE b.entity_status = 'active'
AND ba.city_id='13'
UNION SELECT tg.option AS `text`,
'tags' AS `type`,
tg.option AS `id`,
tg.option AS 'params'
FROM tags t
LEFT JOIN tag_options tg ON (t.id=tg.tag_id)
WHERE t.tag='MBA'
UNION SELECT category AS `text`,
'category' AS `type`,
category AS `id`,
category AS 'params'
FROM categories
UNION SELECT area AS `text`,
'area' AS `type`,
id AS `id`,
id AS 'params'
FROM areas
WHERE city_id='13'
UNION SELECT district AS `text`,
'districts' AS `type`,
id AS `id`,
id AS 'params'
FROM districts
WHERE city_id='13'
UNION SELECT neighbourhood AS `text`,
'neighbourhood' AS `type`,
id AS `id`,
id AS 'params'
FROM neighbourhoods
WHERE city_id='13' ) AS t1
WHERE `text` LIKE 'harv'
OR `text` LIKE 'harv%'
OR `text` LIKE '%harv%'
ORDER BY priority LIMIT 5
基本上,这个问题正在进入排名前5的商学院,这些商学院有文本" harv"在附近的13区,还有学校提供MBA课程,其中有文字" harv"。此查询用于自动完成搜索。它耗时超过1秒,我认为autocompelte非常长。我在这个查询中做错了吗?有没有办法优化这个。
说明:
1 PRIMARY <derived2> ALL NULL NULL NULL NULL 7649 Using where; Using filesort
2 DERIVED ba ref IDX_76AE73698BAC62AF,IDX_76AE7369A89DB457 IDX_76AE73698BAC62AF 5 7458 Using where
2 DERIVED b eq_ref PRIMARY PRIMARY 4 school_live.ba.business_id 1 Using where
2 DERIVED n eq_ref PRIMARY PRIMARY 4 school_live.ba.neighbourhood_id 1
3 UNION t ALL NULL NULL NULL NULL 22 Using where
3 UNION tg ref IDX_E204D72DBAD26311 IDX_E204D72DBAD26311 5 school_live.t.id 4
4 UNION categories ALL NULL NULL NULL NULL 5
5 UNION areas ref IDX_58B0B25C8BAC62AF IDX_58B0B25C8BAC62AF 5 5 Using where
6 UNION districts ref IDX_68E318DC8BAC62AF IDX_68E318DC8BAC62AF 5 5 Using where
7 UNION neighbourhoods ref IDX_49F0CA178BAC62AF IDX_49F0CA178BAC62AF 5 422 Using where
NULL UNION RESULT <union2,3,4,5,6,7> ALL NULL NULL NULL NULL NULL