简体   繁体   中英

how to optimize sql join query

I want to optimize sql query

SET SQL_BIG_SELECTS=1;
SELECT
    `Surveys`.`fname`
    , `Surveys`.`lname`
    , `Surveys`.`smobile`
    , `Surveys`.`semail`    
    , `Surveys`.`country`
    , `Surveys`.`city`    
    , `Surveys`.`sdob`
    , `Brand`.`brandname`
    , `Product`.`productname`        
    , `Surveys`.`outletcode`
    , `Surveys`.`outletname`
    , `Surveys`.`coupon_no`
    , `Users`.`username`
    , DATE_ADD(`Surveys`.datetime, INTERVAL 8 HOUR) as datetime
    , `Surveys`.`duration`    
    , userentry.couponcode as wcouponcode
    , userentry.couponcodecountry
    , userentry.prizename
    , DATE_ADD(userentry.datetime, INTERVAL 8 HOUR) as wdatetime    
FROM
    `Surveys`
    INNER JOIN `Brand` 
        ON (`Surveys`.`brandid` = `Brand`.`brandid`)
    INNER JOIN `Product` 
        ON (`Surveys`.`productid` = `Product`.`productid`) AND (`Surveys`.`brandid` = `Product`.`brandid`)    
    INNER JOIN `Users` 
        ON (`Surveys`.`userid` = `Users`.`userid`)
    INNER JOIN `userentry` 
        ON (`userentry`.`mobile` = `Surveys`.`smobile`)

here if am not writing SET SQL_BIG_SELECTS=1; it doesn't work

even with SQL_BIG_SELECTS its expire(sql timeout),

so how to optimize this query

Please help me

There are always 2 things to consider when optimising queries:

  • What indexes can be used (you may need to create indexes)

  • How the query is written (you may need to change the query to allow the query optimiser to be able to find appropriate indexes, and to not re-read data redundantly)

The keys are:

1.You shouldn't need the subqueries - just do the direct joins and aggregate

2.You should be able to use INNER JOINs, which are typically more efficient than OUTER JOINs

您必须索引在select语句中使用的列(brandId,productid,userid,mobile)

应该为连接中包含的两个表之间的公共列建立索引。

From what the others noted about ensuring an index on the columns you are joining on, I only have one other suggestion. SOMETIMES, the MySQL query optimizer will try to use one of the other tables (such as product, brand, user) as the driving table based on lower counts from those tables or whatever other stats it may have available.

Since your query looks like all the other tables are more "lookup" reference only, and your Surveys table is the critical root table, just change

SELECT (... rest of query)

to

SELECT STRAIGHT_JOIN (... rest of query)

It tells the optimizer to do it in the order you've specified.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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