MySQL很多表连接

时间:2015-03-26 23:58:16

标签: php mysql sql

post_info 表包含许多匹配单个ID的行(多边)。我在输出中返回多行时遇到问题。

enter image description here

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;

我也不确定如何将 board 表写入查询。

用户表:

enter image description here

post_info表:

enter image description here

发布表格

enter image description here

2 个答案:

答案 0 :(得分:2)

这就是你将棋盘写入查询的方式。增加了额外的加入以代表董事会发布关系。

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;  

答案 1 :(得分:1)

你忘记了联接中的棋盘

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