Inner Joining Multiple tables in mysql

霸气de小男生 提交于 2019-12-02 17:24:52

问题


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.


回答1:


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;


来源:https://stackoverflow.com/questions/42472413/inner-joining-multiple-tables-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!