5.Oracle5

1. 子查询:

  1. select 子查询

    -- select 子查询
    select t1.ename, (select dname from dept t2 where t2.deptno = t1.deptno)
    from emp t1
    -- 限制: 不能对应多行
    select dname, (select ename from emp t2 where t1.deptno = t2.deptno)
    from dept t1;
    
  2. from子查询:

​ 根据题意,结果中有跨表的列时用from

  1. where子查询

​ 根据题意,结果中不需要跨表

2. 约束–DDL

  • default : 默认值

  • not null: 非空

    create table student(
    stuno number(5), -- stuno number(5) not null,
    stuname varchar2(20) default '路人甲'
    );
    
    insert into student values(1, null); -- 
    insert into student (stuno) values(2);
    insert into student (stuname) values('路人乙')
    select * from student;
    alter table student modify stuno not null; -- 注意:已有数据不能违反这个约束
    delete from student where stuname='路人乙';
    
    
  • 唯一约束: unique 默认创建唯一索引(提高查询的速度)

    • create table 表名(字段 类型 unique); 默认创建了唯一约束的名字

    • alter table 表名 add constraint 约束名字 约束的类型 (字段1,字段2)

      ---- 唯一 unique 有名字 。默认创建索引(提高查询效率)
      alter table student add constraint Uni_Student_stuno unique (stuno);
      
      truncate table student;
      insert into student values(1, null);
      insert into student values(1, null);
      drop table student;
      
      create table student(
      stuno number(5) not null unique, -- 随机的系统名
      stuname varchar2(20) default '路人甲'
      );
      insert into student values(1, null);
      
  • 主键约束: primary key: === not null + unique ; 创建主键约束,会默认创建索引

    • 关系型数据库ORDBMS: 关系(主外关系)
    
    drop table student;
    create table student(
    stuno number(5) , 
    stuname varchar2(20) default '路人甲'
    );
    
    alter table student add constraint PK_STUDENT_stuno primary key (stuno);
    insert into student values(1, null);
    insert into student values(null, null);
    
  • 外键约束: 外键要关联主键(唯一)

    • 外键的数据是 关联主键中的数据

    • 外键的数据可以为空

    • 在关系n:1

      -- foreign key : 外键: 外键要关联主键(唯一约束)
      -- 外键的内容要在主键中有: 
      select * from emp;
      select * from dept;
      
      create table clazz(
             clazzno number primary key,
             clazzname varchar2(30)
      );
      
      insert into clazz values(1, '2115');
      insert into clazz values(2, '2116');
      insert into clazz values(3, '2117');
      select * from clazz;
      alter table student add clazzno number(4);
      alter table student add constraint FK_Student_clazzno Foreign key (clazzno)
            references clazz(clazzno); -- 背下来
      
      insert into student values(56, 'jerry', 4); -- 违反FK
      insert into student values(56, 'jerry', null); -- 
        select * from student;
        
        commit;
      
posted @ 2021-05-16 11:29  剑心空明  阅读(0)  评论(0编辑  收藏  举报  来源