将一个表多次连接到其他表

uma*_*mar 5 sql

我有三张桌子:

表用户(userid用户名)

表键(userid keyid)

表笔记本电脑(userid laptopid)

我想要所有拥有钥匙或笔记本电脑或两者兼而有之的用户.我如何编写查询,以便它使用表User和表Key之间的连接,以及表User和表Laptop之间的连接?

主要问题是在实际场景中,有十二个左右的表连接,如:

"选择..从左边的连接b开始(...),c连接d on(..),e,f,g where ...",

我看到a可以加入b,a也可以加入f.所以假设我不能使表a,b和f并排出现,我该如何编写sql查询?

And*_*mar 9

您可以使用多个联接来组合多个表:

select *
from user u
left join key k on u.userid = k.userid
left join laptop l on l.userid = u.userid
Run Code Online (Sandbox Code Playgroud)

"左连接"还可以找到没有密钥或笔记本电脑的用户.如果用"内部连接"替换它们,它将只找到有笔记本电脑和密钥的用户.

当"左连接"找不到行时,它将在其字段中返回NULL.因此,您可以选择所有拥有笔记本电脑或密钥的用户:

select *
from user u
left join key k on u.userid = k.userid
left join laptop l on l.userid = u.userid
where k.userid is not null or l.userid is not null
Run Code Online (Sandbox Code Playgroud)

NULL是特殊的,因为你比较它像"field is not null"而不是"field <> null".

在你的评论后添加:说你有一个表鼠标,它与笔记本电脑有关,但与用户有关.您可以加入以下内容:

select *
from user u
left join laptop l on l.userid = u.userid
left join mouse m on m.laptopid = l.laptopid
Run Code Online (Sandbox Code Playgroud)

如果这不能回答你的问题,你需要澄清一些.