Note that there are some explanatory texts on larger screens.

plurals
  1. POMYSQL: Optimize Order By in Table Sort
    primarykey
    data
    text
    <p>I am developing an application for my college's website and I would like to pull all the events in ascending date order from the database. There is a total of four tables:</p> <p>Table Events1</p> <pre><code>event_id, mediumint(8), Unsigned date, date, Index -&gt; Primary Key (event_id) Index -&gt; (date) </code></pre> <p>Table events_users</p> <pre><code>event_id, smallint(5), Unsigned user_id, mediumint(8), Unsigned Index -&gt; PRIMARY (event_id, user_id) </code></pre> <p>Table user_bm</p> <pre><code>link, varchar(26) user_id, mediumint(8) Index -&gt; PRIMARY (link, user_id) </code></pre> <p>Table user_eoc</p> <pre><code>link, varchar(8) user_id, mediumint(8) Index -&gt; Primary (link, user_id) </code></pre> <p>Query:</p> <pre><code>EXPLAIN SELECT * FROM events1 E INNER JOIN event_users EU ON E.event_id = EU.event_id RIGHT JOIN user_eoc EOC ON EU.user_id = EOC.user_id INNER JOIN user_bm BM ON EOC.user_id = BM.user_id WHERE E.date &gt;= '2013-01-01' AND E.date &lt;= '2013-01-31' AND EOC.link = "E690" AND BM.link like "1.1%" ORDER BY E.date </code></pre> <p>EXPLANATION:</p> <p>The query above does two things.</p> <p>1) Searches and filters out all students through the user_bm and user_eoc tables. The "link" columns are denormalized columns to quickly filter students by major/year/campus etc.</p> <p>2) After applying the filter, MYSQL grabs the user_ids of all matching students and finds all events they are attending and outputs them in ascending order.</p> <p>QUERY OPTIMIZER EXPLAIN:</p> <pre><code>id select_type table type possible_keys key key_len ref rows Extra 1 SIMPLE EOC ref PRIMARY PRIMARY 26 const 47 Using where; Using index; Using temporary; Using f... 1 SIMPLE BM ref PRIMARY,user_id-link user_id-link 3 test.EOC.user_id 1 Using where; Using index 1 SIMPLE EU ref PRIMARY,user_id user_id 3 test.EOC.user_id 1 Using index 1 SIMPLE E eq_ref PRIMARY,date-event_id PRIMARY 3 test.EU.event_id 1 Using where </code></pre> <p>QUESTION:</p> <p>The query works fine but can be optimized. Specifically - using filesort and using temporary is costly and I would like to avoid this. I am not sure if this is possible because I would like to 'Order By' events by date that have a 1:n relationship with the matching users. The Order BY applies to a joined table.</p> <p>Any help or guidance would be greatly appreciated. Thank you and Happy Holidays!</p>
    singulars
    1. This table or related slice is empty.
    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