php - Selecting from a Many to Many table -
this question has answer here:
i want post_id , thumbnail of post(s) have multiple tags. tables follow:
table: post ------------------- post_id | thumbnail 1 | 1.jpg 2 | 2.jpg 3 | 3.jpg 4 | 4.jpg 5 | 5.jpg table: tags ----------- tag_id | tag 1 | red 2 | yellow 3 | orange 4 | blue 5 | pink table: post_tags ---------------- post_id | tag_id 1 | 1 1 | 2 1 | 4 1 | 5 2 | 2 2 | 3 3 | 4 3 | 1 3 | 2 4 | 5 4 | 4 5 | 1 5 | 3 5 | 5
i use this, not working: first tags of posts in array, , compare them find if post has 3 tags mentioned.
select post_id post_tags tag_id in ($thistags[0], $thistags[1], $thistags[2], $thistags[3])
do need join or group or something? new sql , php. lot.
if have unique constraint on post_tags(post_id,tag_id), , can verify elements of thistags unique, this:
select post_id post_tags tag_id in ($thistags[0], $thistags[1], $thistags[2], $thistags[3]) group post_id having count(1) = 4
this approach requires elements in $thistags
unique. can work around uniqueness issue in post_tags table (but query above requires unique well.)
there other sql statements, other approaches, can achieve equivalent result, query above concise. (some of other approaches use exists predicates, or use join operations on sets of post_id returned each tag.)
Comments
Post a Comment