Its been a while since I have done any SQL and I am not sure if this problem has an easy solution or not. Also I am a bit of a Noob.
I am trying to put together an image gallery that allows users to use tags in order to search for images and then click on additional tags to refine the search and lower the number of results but I am having a big issue with the queries involved.
This is a simplified version of my current database structure:
( 2 tables with an additional Many-to-Many link table )
CREATE TABLE images(
image_id INT(12) AUTO_INCREMENT,
image_name VARCHAR(128),
PRIMARY KEY(image_id)
)ENGINE= INNODB;
CREATE TABLE tags(
tag_name VARCHAR(64) NOT NULL,
PRIMARY KEY(tag_name)
)ENGINE= INNODB;
CREATE TABLE images_tags_link(
image_id_fk INT(12),
tag_name_fk VARCHAR(64) NOT NULL,
PRIMARY KEY(image_id_fk,tag_name_fk),
FOREIGN KEY(image_id_fk) REFERENCES images(image_id),
FOREIGN KEY(tag_name_fk) REFERENCES tags(tag_name)
)ENGINE= INNODB;
Sample Data:
===images===
___________________________
| image_id | image_name |
|----------|----------------|
| 1 | image_001.jpg |
| 2 | image_002.jpg |
| 3 | image_003.png |
| 4 | image_004.jpg |
| 5 | image_005.gif |
---------------------------
===tags===
_______________
| tag_name |
|---------------|
| Landscape |
| Portrait |
| Illustration |
| Photo |
| Red |
| Blue |
| Character |
| Structure |
---------------
===images_tags_link===
________________________________
| image_id_fk | tag_name_ fk |
|-------------|------------------|
| 1 | Landscape |
| 1 | Illustration |
| 1 | Blue |
| 2 | Blue |
| 2 | structure |
| 2 | Landscape |
| 3 | Illustration |
| 4 | Red |
| 4 | Portrait |
| 4 | Character |
| 5 | Blue |
| 5 | Photo |
--------------------------------
My Problem is with the following Query:
I am looking for a single Query that can select all ‘image_names’ from the IMAGES table that have all the users listed tags, for example a user may search for the ‘Blue’ AND ‘Landscape’ tags which should only output the image_names ‘image_001.jpg’ AND ‘image_002.jpg’.
===INPUT===
The Users chosen tags: ( ‘Blue’ , ‘Landscape’ )
===OUTPUT===
The image_names that have ALL the listed tags: ( ‘image_001.jpg’ , ‘image_002.jpg’ )
Thanks in advance.
2 simple ways to do it.
Either of the following, depending on columns required, number of possible tags, etc.