Join
数据库中的表可以通过键将彼此联系起来,主键是一个列,在这个列中的每一行的值都是唯一的,在表中,每个主键的值都是唯一的,这样就可以在不重复每个表中的所有数据的情况下,把表间的数据交叉捆绑在一起。
以下为表user和表Room的数据
1:引用两个表
找出在Room of boy相关联的用户信息
Select u.user_name,u.user_age,r.room_name from user as u,room as r
Where u.room_id = r.room_id and r.room_name='room of boy'
2:使用关键字join来连接两张表
Select u.user_name,u.user_age,r.room_name
from user as u
join room as r
on u.room_id = r.room_id and r.room_name='room of boy'
Inner join
Inner join 与 join 用法一致
Select u.user_name,u.user_age,r.room_name
from user as u
inner join room as r
on u.room_id = r.room_id and r.room_name='room of boy'
Left join
注意:左连接以左边的表为主体,也就是说会列出左边的表中的所有的数据,无论它是否满足条件。
1:user在左边
Select u.user_name,u.user_age,r.room_name
from user as u
Left join room as r
on u.room_id = r.room_id and r.room_name='room of boy'
2:Room在左边
Select u.user_name,u.user_age,r.room_name
From room as r
Left join user as u
on u.room_id = r.room_id and r.room_name='room of boy'
Right join
注意:左连接以右边的表为主体,也就是说会列出左边的表中的所有的数据,无论它是否满足条件。
1:Room在右边
Select u.user_name,u.user_age,r.room_name
from user as u
Right join room as r
on u.room_id = r.room_id and r.room_name='room of boy'
2:user在右边
Select u.user_name,u.user_age,r.room_name
from room as r
Right join user as u
on u.room_id = r.room_id and r.room_name='room of boy'
Full join
1:user在左边
Select * from user Full join room
2:Room在左边
Select * From room full join user
注意:SQL错误码1054表示没有找到对应的字段名;错误码1064表示用户输入的SQL语句有语法错误
希望能对大家有所帮助。