Note that there are some explanatory texts on larger screens.

plurals
  1. POBasic optimisation with an index for mysql
    primarykey
    data
    text
    <p>i have a question about basic mysql database optimisation. I have 3 tables, Articles, Tags and Taggings (which is a join table).</p> <pre><code>Articles Taggings Tags id id id name article_id name tag_id </code></pre> <p>I am retrieving the articles that exactly match the tags specified, with the following query</p> <pre><code>SELECT *, COUNT(*) AS c FROM articles AS a JOIN taggings AS tng ON a.id = tng.article_id JOIN tags AS t ON t.id = tng.tag_id WHERE t.name IN ("Red","Green") GROUP BY a.id HAVING c = 2 </code></pre> <p>This query is slow, so I did an EXPLAIN, and got the following results:</p> <p><a href="http://dl.dropbox.com/u/2306276/EXPLAIN%20results.png" rel="nofollow noreferrer">alt text http://dl.dropbox.com/u/2306276/EXPLAIN%20results.png</a></p> <p>Now, I don't really understand what I am doing here, but i believe that "type: ALL" is not good, so thought i would add indexes(BTREE) to both article_id and tag_id in the taggings table, and run the query again. <a href="http://dl.dropbox.com/u/2306276/EXPLAIN%20results%202.png" rel="nofollow noreferrer">alt text http://dl.dropbox.com/u/2306276/EXPLAIN%20results%202.png</a> Well that didn't look any better to my uneducated eye, same number of rows as previous one, and the type is still ALL in two of the cases.</p> <p>So could someone tell me where I am going wrong please? will indexes not help me with this problem?</p> <p>My Tag table will remain relatively small, so I thought the query should scan the Tag table for the tags I have specified, and then (through the indexes) be able to instantly retrieve the associated properties, and it should all be very quick, obviously something wrong in my thinking.</p> <p>Thanks</p> <p>[EDIT] - for Jay's comments</p> <p>I added 10k articles, 30k taggings, and 6 tags, also added 2 indexs on tag.name and taggings.tag_id, the query still took a long time to run, 0.5-1 second, the EXPLAIN is below. <a href="http://dl.dropbox.com/u/2306276/EXPLAIN%20results%203.png" rel="nofollow noreferrer">alt text http://dl.dropbox.com/u/2306276/EXPLAIN%20results%203.png</a></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.
 

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