简体   繁体   中英

MySQL many table join

post_info table contains many rows (many side) matching a single id. I'm having trouble returning more than one row in my output.

在此处输入图片说明

SELECT user.*, post.*, post_info.*, board.* FROM user 
join post ON user.id = post.user_id
join post_info ON post.id = post_info.post_id 
WHERE user.id = 26;

I'm also not sure how to write my board table into the query either.

user table:

在此处输入图片说明

post_info table:

在此处输入图片说明

post table:

在此处输入图片说明

This is how you write you board table into the query. Additional join was added to represent the board to post relationship.

SELECT user.*, post.*, post_info.*, board.* FROM user 
join post ON user.id = post.user_id
join post_info ON post.id = post_info.post_id 
join board ON board.id = post.board_id
WHERE user.id = 26;  

You forgot board table in joins

SELECT 
    board.id     AS board_id,
    post_info.id AS info_id,
    user.id      AS user_id,
    post_id      AS post_id
FROM post
LEFT JOIN post_info ON 
    post_info.post_id=post.id
LEFT JOIN user ON 
    user.id=post.user_id
LEFT JOIN board ON 
    board.id=post.board_id
WHERE user.id = 26

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM