内部连接 mysql 中的多个表
Inner Joining Multiple tables in mysql
我的数据库中有三个表
用户、帖子和评论。
它们的结构如下:
**users** :
user_id , user_name
**posts**:
post_id , post_content, user_id
**comments** :
comment_id , comment_content , post_id, user_id
现在我想通过以下方式使用连接从这三个表中获取数据:
comment_id、comment_content、user_id、user_name、post_id
谁能告诉我如何做到这一点?
我会很感激的。
很简单JOIN
。
试试这个:
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;
如果您也需要帖子 table 中的专栏,请加入:
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;
我的数据库中有三个表 用户、帖子和评论。
它们的结构如下:
**users** :
user_id , user_name
**posts**:
post_id , post_content, user_id
**comments** :
comment_id , comment_content , post_id, user_id
现在我想通过以下方式使用连接从这三个表中获取数据: comment_id、comment_content、user_id、user_name、post_id 谁能告诉我如何做到这一点? 我会很感激的。
很简单JOIN
。
试试这个:
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;
如果您也需要帖子 table 中的专栏,请加入:
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;