Question

Let's say I have two tables as follows

files
------------
|file_id|name|
|1      |a   |
|2      |b   |
|3      |c   |


files_tags_associations
------------
|associationId|file_id|tag_id|
|1            |1      |3     |
|2            |2      |3     |
|3            |2      |4     |
|4            |3      |3     |
|5            |3      |4     |
|6            |3      |5     |
|7            |3      |6     |

The question is, how do I get the file names that are tagged 3 AND 5? In this case c

SELECT f.name from files f LEFT JOIN files_tag_associations fta ON fta.file_id = f.fileId

....and then I'm lost

Was it helpful?

Solution

SELECT f.name
FROM files as f
INNER JOIN (SELECT file_id
            FROM files_tags_associations
            WHERE tag_id IN (3,5)
            GROUP BY file_id
            HAVING COUNT(*) = 2) as ft
    ON f.file_id = ft.file_id
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top