SQL多重连接整理

时间:2013-06-16 10:19:31

标签: mysql sql join

我有这样的声明:

SELECT board.*,numlikes 
FROM board
LEFT JOIN (
    SELECT pins.board_id, COUNT(source_user_id) AS numlikes
    FROM likes 
    INNER JOIN pins ON pins.id = likes.pin_id 
    GROUP BY pins.board_id
) likes ON board.id = likes.board_id
WHERE who_can_tag='' 
ORDER BY numlikes DESC 
LIMIT 10

然后,我可以使用board".$info['board_name']."中提取行。 但是,我不熟悉多个连接,除了boardlikes表之外,我还需要加入另一个表。 第三个表格为user,并与board.user_id匹配user.user_id

如何使用此数据从user中提取用户名?

".$info['username']."不会username在表board中搜索字段{{1}}吗?

1 个答案:

答案 0 :(得分:1)

这将做你想要的:

SELECT board.*,
    `user`.username,
    numlikes 
FROM board
INNER JOIN `user` ON board.user_id = `user`.user_id
LEFT JOIN (
    SELECT pins.board_id, COUNT(source_user_id) AS numlikes
    FROM likes 
    INNER JOIN pins ON pins.id = likes.pin_id 
    GROUP BY pins.board_id
) likes ON board.id = likes.board_id
WHERE who_can_tag='' 
ORDER BY numlikes DESC 
LIMIT 10