简体   繁体   中英

How to use join for more than two table?

I have three tables.They are

tb_albums ---->id,title, description

tb_photos ---->id,album_id, photo

tb_tags ---->id,album_id, tag

Here i want to get the albums details and it photos & it tags through tb_albums.id .

How to use join query here?

Normally, you can use as many tables in JOIN, as you'd like. Just add another JOIN statement. You can refer to k102's answer for the correct syntax (which doesn't produce correct result though).

But in this particular case you don't want to use simple JOIN on all tables, unless you have only one photo per album and only one tag per album. If you have more than one photo per and more than one tag per album, JOIN both tables on album_id in single query will produce Cartesian product of both, in other words all possible combinations of tags and photos from each albums. For N photos and M tags that's N * M results, instead of N + M .

Also, there is no point of joining with tb_albums, as you do not need to repeat information about each album for each photo and each tag.

Proper approach would be to have 3 separate simple SELECTs from each table and combining their result on application level.

If for some awkward reason you'd need to do that with one query, you can do something like:

SELECT * FROM tb_albums as A JOIN 
 (SELECT 'photo', id, photo as value FROM tb_photos 
  UNION ALL
  SELECT 'tag', id, tag as value FROM tb_tags) as B ON B.album_id = A.id

Note, this is way less optimal than separate SELECTs, you should only do this if you have no other choice.

select * from tb_albums a
join tb_photos p on a.id = p.album_id
join tb_tags t on a.id = t.album_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM