I have three tables
table name: tags
id (int)
tag_name (vharchar)
table name: messages
id (int)
message_title (vharchar)
message_content(vharchar)
table name: message_tag
message_id (int)
tag_id (int)
I have tried this code but it didn’t work(returns empty)
SELECT messages.message_title, messages.message_content, tags.tag_name
FROM messages
INNER JOIN message_tag ON messages.id = message_tag.message_id
INNER JOIN tags ON tags.id = message_tag.tag_id
WHERE message_tag.tag_id =191
AND message_tag.tag_id =19
AND message_tag.tag_id =31
ORDER BY RAND( )
LIMIT 20
I want to select random 20 rows which are connected to tag 191, 19 and 31
Use
INinstead ofAND. This will bring you messages which are linked to one at least of those particular tags.Update: IF you wanted to get messages where all 3 tags are present, you would do this instead (assuming your rows in message_tag are unique):