Note that there are some explanatory texts on larger screens.

plurals
  1. POMySQL Query Optimization - Random Record
    primarykey
    data
    text
    <p>I'm having a terrible time with a MySQL query. I've spent most of my weekend and most of my day today attempting to make this query run a bit faster. I've made it considerably faster, but I know I can make it better.</p> <pre><code>SELECT m.id,other_fields,C.contacts_count FROM marketingDatabase AS m LEFT OUTER JOIN (SELECT COUNT(*) as contacts_count, rid FROM contacts WHERE status = 'Active' AND install_id = 'XXXX' GROUP BY rid) as C ON C.rid = m.id WHERE (RAND()*2612&lt;50) AND do_not_call != 'true' AND `ACTUAL SALES VOLUME` &gt;= '800000' AND `ACTUAL SALES VOLUME` &lt;= '1200000' AND status = 'Pending' AND install_id = 'XXXXX' ORDER BY RAND() </code></pre> <p>I have an index on 'install_id', 'category' and 'status' but the EXPLAIN shows it was sorting based on 9100 rows.</p> <p>My Explain is here: <a href="https://s3.amazonaws.com/jas-so-question/Screen+Shot+2012-03-13+at+12.34.04+AM.png" rel="nofollow">https://s3.amazonaws.com/jas-so-question/Screen+Shot+2012-03-13+at+12.34.04+AM.png</a></p> <p>Anybody have any suggestions on what I can do to make this a bit faster? The entire point of the query is to select a random record from an account's records (install_id) that matches certain criteria like sales volume, status and do_not_call. I'm currently gathering 25 records and caching it (using PHP) so I only have to run this query once every 25 requests, but I'm already dealing with thousands of requests per day. It currently takes 0.2 seconds to run. I realize that by using ORDER BY RAND() I'm already taking a major performance hit, but it's just sorting 25 rows.</p> <p>Thanks in advance for the help.</p> <p>**EDIT: I forgot to mention that the 'contact_sort' index is on the 'contacts' table, and indexes install_id, status, and rid. (rid references Record ID in marketingDatabase so it knows which record a contact belongs to.</p> <p>**EDIT 2: The 2612 number in the query represents the number of rows in marketingDatabase that match the criteria (install_id, status, actual sales volume, etc.)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload