在MySQL上以嵌套方式进行内连接

时间:2012-02-02 09:33:08

标签: mysql sql database

这是我的计划:

board(name, catId)
cat(id, catName)
userBoard(boardName, username)
msg(boardName, username, title, text)

假设用户名是“foo”。我试图实现以下,但不知道如何做到这一点。

对自然加入感兴趣

userBoard.username = "foo" AND userBoard.boardName = board.name AND board.catId = cat.id AND msg.username = "foo" AND msg.boardName = board.name

MySQL的查询是什么?

更新: 我忘了提到我对以下返回值感兴趣

`board.name, cat.catName, msg.title, msg.text`

2 个答案:

答案 0 :(得分:1)

试试这个:

Select b.name, c.catName, m.title, m.text
from board b
   inner join Cat c on b.catId = c.id
   inner join userBoard ub on b.name = ub.boardName
   inner join msg on m b.name = m.boardName
where ub.username = "foo" and m.username = "foo"

您需要根据要从表格中选择的内容选择联接类型。

答案 1 :(得分:0)

select b.name, c.catName, m.title, m.text
from board b
  inner join cat c on b.catId = c.id
  inner join userBoard ub on b.name = ub.boardName
  inner join msg m on b.name = m.boardName
where ub.username = "foo" and m.username = "foo"