Reputation: 347
I Have three tables in my database users , posts and comments.
Their Structure is as follow :
**users** :
user_id , user_name
**posts**:
post_id , post_content, user_id
**comments** :
comment_id , comment_content , post_id, user_id
now i want to fetch data from these three tables using join in a following way : comment_id, comment_content, user_id, user_name, post_id can anyone plz tell me that how this can be done ? I Shall be very thankful.
Upvotes: 0
Views: 652
Reputation: 39467
It's a simple JOIN
.
Try this:
select c.comment_id,
c.comment_content,
u.user_id,
u.user_name,
c.post_id
from comments c
join users u on u.user_id = c.user_id;
If you need columns from posts table too, join it:
select c.comment_id,
c.comment_content,
u.user_id,
u.user_name,
p.post_id,
p.post_content
from comments c
join users u on u.user_id = c.user_id
join posts p on c.post_id = p.post_id;
Upvotes: 1