How to do Query Optimization in MySQL?

Discussion in 'Databases' started by sheril123, Nov 26, 2011.

  1. #1
    SELECT scat.subcatid, scat.catid, COUNT(*) as adcnt
    FROM xzclf_ads a USE INDEX (adsIndex)
    INNER JOIN xzclf_subcats scat USE INDEX (subcatsIndex) ON scat.subcatid = a.subcatid AND (a.enabled = '1' AND a.verified = '1' AND a.expireson >= NOW())
    INNER JOIN xzclf_cats cat USE INDEX(catidIndex) ON cat.catid = scat.catid
    INNER JOIN xzclf_cities ct USE INDEX(cityidIndex) ON a.cityid = ct.cityid
    WHERE scat.enabled = '1'
    AND ct.countryid = 1
    GROUP BY a.subcatid;
    Could some one optimize this query. This query is taking more time to execute.
     
    sheril123, Nov 26, 2011 IP
  2. Shiplu

    Shiplu Peon

    Messages:
    42
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Without watching the schema it can not be determined properly.

    How frequent you run this query?? If you can cache the result of about 1 hour at least it'll be a great improvement.
    Execute this query and save the result to another table.
    Then if the table is 1 hour old update the table. This can be done by a cron.
     
    Shiplu, Nov 28, 2011 IP
  3. iliveforyou

    iliveforyou Active Member

    Messages:
    207
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    53
    #3
    i change your query

    SELECT scat.subcatid, scat.catid, COUNT(*) as adcnt
    FROM xzclf_ads a USE INDEX (adsIndex)
    INNER JOIN xzclf_subcats scat USE INDEX (subcatsIndex)
    INNER JOIN xzclf_cats cat USE INDEX(catidIndex) ON cat.catid = scat.catid
    ON scat.subcatid = a.subcatid
    AND (a.enabled = '1' AND a.verified = '1'
    AND a.expireson >= NOW())
    INNER JOIN xzclf_cities ct USE INDEX(cityidIndex) ON a.cityid = ct.cityid
    WHERE scat.enabled = '1'
    AND ct.countryid = 1
    GROUP BY a.subcatid;
     
    iliveforyou, Nov 28, 2011 IP
  4. iliveforyou

    iliveforyou Active Member

    Messages:
    207
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    53
    #4
    second solution

    SELECT scat.subcatid, scat.catid, COUNT(*) as adcnt
    FROM xzclf_ads a USE INDEX (adsIndex)
    INNER JOIN xzclf_subcats scat USE INDEX (subcatsIndex)
    INNER JOIN xzclf_cats cat USE INDEX(catidIndex) ON cat.catid = scat.catid
    ON scat.subcatid = a.subcatid
    AND (a.enabled = '1' AND a.verified = '1'
    AND a.expireson >= NOW())
    AND scat.enabled = '1'
    INNER JOIN xzclf_cities ct USE INDEX(cityidIndex)
    ON a.cityid = ct.cityid
    AND ct.countryid = 1
    GROUP BY a.subcatid;
     
    iliveforyou, Nov 28, 2011 IP
  5. Rukbat

    Rukbat Well-Known Member

    Messages:
    2,908
    Likes Received:
    37
    Best Answers:
    51
    Trophy Points:
    125
    #5
    Are the fields you're looking at in the indexes you're using? If not, you're doing a sequential lookup, and it'll be slow.
     
    Rukbat, Dec 1, 2011 IP