SQLServer单表多表连接语句总结..docxVIP

  • 4
  • 0
  • 约6.46千字
  • 约 7页
  • 2017-06-12 发布于北京
  • 举报
一:使用内部连接??????????????即将两个表中的列进行比较将两个表中满足连接条件的行进行组合起来作为结果他是最长见的表连接形式?????????????在内部连接中表的地位是平等的?????????????内部连接的语法形式:??????????????1. select??选择列表??from??表名1,表名2??where 表名1.列名1 = 表名2.列名2???????????????????Eg: select emplName,deptName from??employees emp,depts dept where emp.deptID = dept.deptID;??????????????2. select 选择列表 from???表名1 [inner]??jion??表名2 on??表名1.列名1 = 表名2.列名2???????????????????Eg: select??emplName,deptName from employees emp inner join depts dept??on dept.deptID = emp.deptID;二:使用外部连接?????????????会返回from子句中提到的至少一个表的所有行只要这些行符合任何where 或having 搜索条件?????????????参与连接的表有主从之分以主表的每行数据去匹配从表的数据列符合连接条件的列将直接返回到结果集中对那些不符合连接条件的列将被添上null后返回到结果集中?    外部连接分为:      1.左外部链接(left join)?        ????左外部连接对连接条件中左表的表不加限制即结果表中保留左关系表的中所有元组          Eg:查看各个员工所在的部门要求显示所有员工所在的部门没有部门的员工也要显示出来          select emplName,emplAge,deptName from employees emp left join depts dept on dept.deptID =emp.deptID;      2.右外部连接(right join)??         ??右外连接??对连接条件中右边的表不加限制??即结果表中保留右关系表中的所有元组          Eg:查看在各个部门中有那些员工要求显示部门中不所有员工没有员工的部门也要显示出来          select emplName,emplAge,deptName from employees emp right join depts dept on dept.deptID =emp.deptID;      3.全外连接(full outer join)?????????????  ?????????全外连接??对两个表都不加限制??所有两个表中的行都会包括在结果集中???????????????    ???Eg:也就是说将没有部门的员工显示出来没有员工的部门显示出来          select emplName,emplAge,deptName from employees emp full outer join depts dept on dept.deptID =emp.deptID;?????????????????三:使用交叉连接(cross join)?????????????交叉连接即非限制连接她将两个表不加任何限制的组合起来没有where子句的交叉连接将产生连接所涉及的表的笛卡尔积??????????????Eg:select emplName,emplAge,deptName from employees emp corss jion depts dept;????????????四:使用自连接????????????使用自连接可以看作是一个表的两张副本在连接?????????????Eg:select emp.emplName,emp.emplAge from employees emp,employees emp2???????????????????????where emp.emplAge = emp2.emplAge and emp2.emplName=钱二;????????????五:多表连接?  一个简单的例子:?    ?--顾客买了什么产品??多少数量?    ??--第一种方法    ??    ??--select 选择列表 from 选择列表所在的表名 where    ??--表名1.列名1=表名2.列名2 and 表名3.列名3 =表名2.列名2.2    ??--第二种方法??    ?    ?--select 选择列表 from 表

文档评论(0)

1亿VIP精品文档

相关文档