SQL-子查询

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qqxyy99/article/details/54236077

     最近在和小伙伴搭档补漏洞,之前学过的知识大多是囫囵吞枣,一知半解的样子,为了复习巩固,外加自制力差,就和小伙伴组团学习了。现阶段是SQL语句的使用。在学到第六章SQL子查询中遇到以下几个问题:

     1.已经创建好的表中添加外键: 

     通常我们会通过语句来创建表与表之间的主外键关系,如下:

    Create table User
       (UserId int not null primary key,
        UserName char(10));

    Create table Student
     (StudentId int not null
        foreign key (StudentId) references User(UserId) ,
        StudentName char(10));


      但是如果我们已经完成表字段的基本创建,但是忘记添加主外键联系了,又不能重新执行语句来创建表,那么该怎么办呢?直接在表中添加外键即可,如下所示:

   

       在外键表中右击选择关系→添加关系→表和列规范→选取所需主外键表及字段→成功建立关系

很简单,也很方便。

       2.用语句实现在原表中添加较多字段时,例:向students中添加StudentAge字段

          alter table dbo.students add StudentAge int; 

          通用的为alter table 表名 add 列名 类型,删除等类似。

       3.含有IN和EXISTS的子查询

        select * from orderHeader  where custId in(1,3,4);  --这里的IN需要的是一个值的列表,表示的是一种与值的“等于”关系(即custId=1 or custId=3 or custId=4)

        select orderId,orderDate,shipTo from orderHeader where custId in(1,3,4);--这里必须建立主外键联系才能进行连接查询,不过这里写的不灵活,必须知道customer中custId中shipTo的具体地点,可修改为下


        select orderId,orderDate,shipTo from orderHeader where custId in(select custId from customers where city = 'Beijing');--为什么显示不出来结果呢?不科学


        select cutName,city from customers where exists(select * from orderHeader where custId=customers.custId);
        通常情况下,含EXISTS的是相关子查询,含IN的是独立子查询,大家可以区分开吗?


           漏洞还在继续补,子查询这章还没补完呢。。

猜你喜欢

转载自blog.csdn.net/qqxyy99/article/details/54236077