Sql Server数据库之多表查询

一.连接查询

  概念:根据两个表或多个表的列之间的关系,从这些表中查询数据

  目的:实现多表查询操作

  语法:From join_table join_type join_table[ON(join_condition)]

      join_table:连接的表名

      join_type:连接类型

      join_condition:连接条件

  连接类型:内连接,外连接,交叉连接

二.内连接

  1.等值连接

    概念:在连接条件中使用"="运算符,其查询结果中列出被连接表中的所有列,包括其中的重复列

扫描二维码关注公众号,回复: 4898738 查看本文章

    示例:

 1 create table student
 2 (
 3     studentId int not null primary key,
 4     studentName nvarchar(20) not null,
 5     classId int not null
 6 )
 7 create table class
 8 (
 9     classId int not null primary key,
10     className nvarchar(20) not null
11 )
12 insert into student values(1,'岳云鹏',1);
13 insert into student values(2,'郭德纲',1);
14 insert into student values(3,'郭麒麟',1);
15 insert into student values(4,'孙越',2);
16 insert into student values(5,'于谦',2);
17 insert into student values(6,'阎鹤翔',2);
18 insert into class values(1,'逗哏班');
19 insert into class values(2,'捧哏班');
20 select * from student s inner join class c on s.classId = c.classId 

  2.不等值连接

    概念:在连接条件中使用除等号之外的运算符

    示例:

1 select * from student s inner join class c on s.classId != c.classId

三.外链接

  1.左连接

    左表结构:

      

    右表结构:

      

     左连接查询:

select * from student s left join class c on s.classId = c.classId

     查询结果:

          

  总结:左连接:返回左表中的所有行,如果左表行在右表中没有匹配行,则结果中右表中的列返回控制

  2.右连接

     右连接查询: 

      

select * from student s right join class c on s.classId = c.classId

     查询结果:

      

   总结:右连接:恰与左连接相反,返回右表中的所有行,如果右表中行在左表中没有匹配行,则结果中左表中的列返回空值。

  3.全连接

    全连接查询

select * from student s right join class c on s.classId = c.classId

    查询结果

      

    总结:全连接:返回左表和右表中的所有行,当某行在另一表中没有匹配行,则灵异表中的列返回空值

四.交叉连接(笛卡尔积)

  1.不带where子句

    执行交叉连接:

select * from student cross join class

    查询结果:

      

  2.带where子句

    执行交叉连接:

select * from student s cross join class c where s.classId = c.classId

    查询结果:

  

    

  

猜你喜欢

转载自www.cnblogs.com/alan-1996/p/10262452.html