sql连接查询

连接查询

1.       对同一个表的操作叫做自连接。

自连接:等值连接、不等连接和自连接。

From join_table join_type join_table [ON (join_condition)]

注:join_type(连接类型) join_table(表名)

===================================================================

1)内连接

不等连接:包括>,>=,<,<=,!>,!<,<>

不等连接的2种写法:

例:

         Select username,userid from users inner join orders on users.userid<>orders.userid

常用:slelct u.username,o.userid from users u, orders o where u.userid<>o.userid

 

等值连接:等值连接用“=”运算符连接对应的主外键

 

自连接:使用同一个表进行比较

例:

我们要查出demo表员工和对应的上级

Select a.user_namer as ’上级’,b.user_namer as ‘员工’ from demo as a ,demo as b where

a.userid=b.user_level

(b.user_level 对应的员工编号)

===================================================================

2)外连接

左连接left join从左表(table_name1)返回所有行,即使右表(table_name2)中没有匹配的行

右连接right join从右表(table_name2)返回所有行,即使左表(table_name1)中没有匹配的行(提示:某些数据库中rhigt join称为right outer join)

完整连接full join从左表和右表返回所有行。左表中行在右表中没有匹配,或者右表中的行在左表中没有匹配,这些行同样会列出来。

原文地址:https://www.cnblogs.com/tangge/p/1930148.html