user3030712 user3030712 - 6 months ago 13
SQL Question

MYSQL how to select this between 3 tables

I have 3 tables.

Table 'posts'

post_id post_content post_topic
1 "Test" 1
2 "How are you" 1
3 "Hey" 1
4 "What" 2


Table 'topics'

topic_id topic_name topic_forum
1 "Test 1" 1
2 "Test 2" 2


Table 'forums'

forum_id forum_name
1 "Food"
2 "Game"


I want to select all records from posts where post_topic -> topic_forum = 1


So in this case I supposed to use JOIN?

Can someone explain me how to? Thanks.

Answer

This will list all posts where topic_forum is 1.

select * from posts p 
left join topics t 
    on t.topic_id = p.post_topic
where t.topic_forum = 1

To list all posts where forum_name = 'Food'

select * from posts p 
left join topics t 
    on t.topic_id = p.post_topic
left join forums f
    on f.forum_id = t.topic_forum
where f.forum_name = 'Food'
Comments