简体   繁体   English

查询效果:按邮政编码,公司名称或城镇搜索

[英]Query Performance: Search by postcode, company name or town

See the SQL query below - it allow you to search the Shop by Postcode, Company Name or Town (location)... On the frontend website there will be only one search textbox without dropdown search type. 请参阅下面的SQL查询-它允许您按邮政编码,公司名称或城镇(位置)搜索商店...在前端网站上,只有一个搜索文本框,没有下拉搜索类型。

It will only show the result if shop_options.live is equal to 1 and depending which day shop is open: O_Hour.weekday = '5' (Friday). 仅当shop_options.live等于1并取决于开店的那一天时,才会显示结果: O_Hour.weekday = '5' (星期五)。

If I search by S_D.postcode (for example: S_D.postcode = 'L14' ) it will then find L14 from shop_delivery_area table and then display list of shops from that postcode. 如果我通过S_D.postcode搜索(例如: S_D.postcode = 'L14' ),它将从shop_delivery_area表中找到L14,然后显示该邮政编码中的商店列表。

SELECT distinct S.*, S.company, S.street, S.town FROM shop as S
    JOIN shop_delivery_area as S_D on S_D.shopID = S.shopID
    JOIN shop_options on shop_options.shopID = S.shopID
    JOIN shop_opening_hours as O_Hour on O_Hour.shopID  = S.shopID
WHERE (S_D.postcode = 'Liverpool'  OR S.company LIKE 'Liverpool' OR S.town LIKE 'Liverpool') 
AND shop_options.live = '1' AND O_Hour.weekday = '5' 
    ORDER BY O_Hour.opentime

The query does work but its very slow. 该查询确实可以工作,但是非常慢。 Almost a second to get the result. 差不多一秒钟就能得到结果。 How to improve the performance faster? 如何更快地提高性能?

Edit: Fixed SQL query. 编辑:修复了SQL查询。

If you need to keep the predicates ie 如果您需要保留谓词,即

S_D.postcode = 'Liverpool'  OR S.company LIKE 'Liverpool' OR S.town LIKE 'Liverpool'

Then consider adding indexes on the same columns. 然后考虑在同一列上添加索引。 So: 所以:

ALTER TABLE shop_delivery_area ADD KEY `sda_idx1` (`postcode`);
ALTER TABLE shop ADD KEY `shop_idx1` (`company`);
ALTER TABLE shop ADD KEY `shop_idx2` (`town`);

One other point is about fuzzy searching. 另一点是关于模糊搜索。 If you can replace the 'LIKE' with an '=' then you'll see a speed increase. 如果您可以将'LIKE'替换为'=',那么速度将会提高。 There's not much point using 'LIKE' with no fuzzy searching though ie LIKE 'Liverpool'. 使用'LIKE'进行模糊搜索没有多大意义,尽管也可以使用'LIKE'Liverpool'。 Use either LIKE '%Liverpool%' or = 'Liverpool'. 使用LIKE'%Liverpool%'或='Liverpool'。 So either use: 因此,请使用:

    S_D.postcode = 'Liverpool'  OR S.company LIKE '%Liverpool%' OR S.town LIKE '%Liverpool%'

or 要么

    S_D.postcode = 'Liverpool'  OR S.company = 'Liverpool' OR S.town = 'Liverpool'

If you use the latter and create the indexes then your query should run just fine! 如果使用后者并创建索引,则查询应该可以正常运行!

使用IFNULL代替OR可以显着提高性能,具体取决于您的数据量,索引等。

  1. Get rid of conditions for empty strings ( S_D.postcode = '' OR S.company LIKE '' ) 摆脱空字符串的条件( S_D.postcode = '' OR S.company LIKE ''
  2. Generally LIKE will slow down your queries a lot, so I'll avoid it whenever it's possible 通常,LIKE会大大降低您的查询速度,因此,我会尽可能避免使用它
  3. Add indexes on WHERE columns 在WHERE列上添加索引

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM