Question

I am trying to optimize mysql to decrease my server load.. And here i have a complex query which will be used about 1k times/minute on a quad core server with 8gb ram and my server is going down.

I have tried many ways to rewrite this query :

SELECT * 
  FROM (
    SELECT  a.id, 
            a.url 
    FROM surf a 
        LEFT JOIN users b 
            ON b.id = a.user 
        LEFT JOIN surfed c 
            ON c.user = 'asdf' AND c.site = a.id 
    WHERE   a.active = '0' 
        AND (b.coins >= a.cpc AND a.cpc >= '2') 
        AND (c.site IS NULL AND a.user !='asdf') 
   ORDER BY a.cpc DESC, b.premium DESC 
      LIMIT 100) AS records 
ORDER BY RAND() 
   LIMIT 1

But it didn't work. So can you guys help me to rewrite the above query so that it would not waste any resources ?

Also this query doesn't have any indexes :( . It would be very helpful to guide me creating indexes for this.

Was it helpful?

Solution

The problem is most likely the inner sort.

You should have indexes on surfed(site, user, cpc), surf(active, user, site), and user(id, coins).

You can also perhaps make minor improvements by switching the join to inner joins from outer joins. The where clause is undoing the left outer join anyway, so this won't affect the results.

But I don't think these changes will really help. The problem is the sort of the result set in the inner query. The outer sort by rand() is a minor issue, because you are only doing that on 100 rows.

If you are running this 1,000/minute, you will need to rethink your data structures and develop an approach that has the data you need more readily available.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top