Note that there are some explanatory texts on larger screens.

plurals
  1. POJoining 3 tables in MYSQL and filtering
    primarykey
    data
    text
    <p>This is a follow up of my <a href="https://stackoverflow.com/questions/5120859/joining-3-tables-efficiently-in-mysql">previous question</a>, but is slightly different and merits it's own question.</p> <p>I have 3 tables like this:</p> <p>images (~10,000 rows)</p> <pre><code>id | place_id | filename ---|----------|---------- 1 | 4 | abc.jpg 2 | 3 | def.jpg 3 | 4 | ghi.jpg 4 | 7 | jkl.jpg </code></pre> <p>tags (~100 rows)</p> <pre><code>id | name | ---|----------| 1 | tagA | 2 | tagB | 3 | tagC | 4 | tagD | </code></pre> <p>tagsToImages (~30,000 rows)</p> <pre><code>id | tag_id | image_id ---|----------|---------- 1 | 1 | 4 2 | 3 | 2 3 | 2 | 4 4 | 1 | 1 </code></pre> <p>As an example, the last table shows that the tag with id = 1 is linked with the image with id = 4.</p> <p>What I'd like to do is to select all the images with a certain place_id, and associate each image with a list of tags like so:</p> <p>Select all with place_id = 4, whilst joining to tags info.</p> <pre><code> filename | tags ----------------------- abc.jpg | tagA ghi.jpg | tagA, tagB </code></pre> <p>A query to do that was suggested by <a href="https://stackoverflow.com/users/232403/a1ex07">a1ex07</a>, and looks like this:</p> <pre><code>SELECT i.filename, GROUP_CONCAT(t.name SEPARATOR ',') AS tags FROM images i INNER JOIN tagsToImages tti ON (tti.image_id = i.id) INNER JOIN tags t ON (t.id = tti.tag_id) WHERE i.place_id = 4 GROUP BY i.filename </code></pre> <p>This is fantastic, and works really well. What I'd like to do now is to filter that set of results by specifying a tag as well as a place.</p> <p>My attempt of:</p> <pre><code>SELECT i.filename, GROUP_CONCAT(t.name SEPARATOR ',') AS tags FROM images i INNER JOIN tagsToImages tti ON (tti.image_id = i.id) INNER JOIN tags t ON (t.id = tti.tag_id) WHERE i.place_id = 4 AND t.id = 3 GROUP BY i.filename </code></pre> <p>Almost works, but it only includes images that exclusively have tag with id 3, not images with lots of tags, one of which has id 3.</p> <p>Can any one help me out?</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.
    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