I need help building a mysql query to select from multiple tables.
I have three database tables related to images: images
, tags
, tag_asc
. I want to fetch an image data and its tag names by providing image_id
.
For example, following is my tables structure:
images:
image_id image_name path date
1 test.jpg dir 1311054433
tags:
ta开发者_StackOverflowg_id image_id
1 1
2 1
tag_asc:
tag_id tag_name
1 "first"
2 "second"
3 "third"
I want to fetch the data of an image with image_id = 1
from images table and all tag names associated with image_id=1
from tag_asc
table.
I'm using CodeIgniter Active records, but I just need idea of joining the tables.
Thanks for any help.
select *
from images i
left join tags t on t.image_id = i.image_id
left join tag_asc ta on ta.tag_id = t.tag_id
where i.image_id = 1;
Using LEFT JOIN
means that rows will be returned even if there are no joining rows in the other tables (but you'll get null
values in the columns for the missing rows), which is typically desirable.
If you want one row (not stated in question, but in comments), use this:
select i.image_id, group_concat(tag_name) as tag_names
from images i
left join tags t on t.image_id = i.image_id
left join tag_asc ta on ta.tag_id = t.tag_id
where i.image_id = 1
group by 1;
精彩评论