您的位置:首页 > 数据库

sql 入门(primary and intermediate)

2020-02-03 22:05 1461 查看

文章目录

  • (5) Set Operations
  • (6) NULL
  • (7) Aggregate Functions
  • (8) Nested Sub-queries
  • 4. Modification operations
  • 5. Join Expression
  • sql intermediate
  • some tools
  • sql primary

    1. Basic type

    简单例子如下:

    char(n) \ varchar(n)		//n is max_len; unit: 1Byte
    int \ smallint
    numeric(p,d)		//precision(有效数字), digit(小数的位数)
    real \ double precision \ float(n)

    sql基本类型详见:
    http://www.w3school.com.cn/sql/sql_datatypes.asp

    2. Creating table instruction

    create table r
    (Ai   Di,	//属性、基本类型
    ...
    <integrity constraint>,
    ...)	//主要是三大约束:主键、外键、not null

    example:

    常用建表约束:

    primary key
    (attribute)
    foreign key
    (attribute1)
    references
    oth_table(attribute2)
    (如果attribute1和attribute2是相同的String,那么attribute2,可以省略,就是直接写oth_table即可)
    attribute type
    not null

    check
    详见:http://www.w3school.com.cn/sql/sql_check.asp

    3. Query operations

    (1) single relation query

    1. 即 只从一个 table(表)中查询

    2. 查询语句的

      principle

      六大语句的逻辑顺序
    3. 任何输入输出都是表(table or relation)
  • 如何去重复?关键字:

    distinct
    ,
    all(default)

  • select distinct Ai
    from r
    1. select clause 的参数可以是:某属性、常数、含有+ - * / 的算术表达式
    2. where clause:是作用在from clause产生关系的属性上的谓词P
    3. where clause 中可以使用:
      逻辑连接词:and、or、not
      比较运算符: <,<=,>,>=,=,<>(!=)

    (2) multiple relation query

    1. 即从 两个及以上 的表中查询
    2. cross join
      : from r1,r2,…rn, 创建了一个大的笛卡儿积(元组乘元组)

    (3) Natural Join

    1. natural join
      连接两个关系的
      相同属性
      取值相同
      的所有元组
    2. 一般的使用格式:from E1,E2,…
      (Ei can be single relation or multi-relation)
    3. 为了避免不必要(多余的)的相同属性带来的危险,使用
      join...using(Ai)

      (显示指明相同属性,且仅限于属性)

    (4) Additional Basic Operations

    a) rename opr

    1. 格式: old-name as new-name
    2. 变量别名 vs 表别名(table alias, correlation name\variable, tuple variable)

    b) string opr

    1. 单引号标识, 如 ‘str’ (这个容易忘)
    2. 如果字符里有单引号,则用双引号,如"it"s right "
    3. 字符串函数: upper(s), trim(s), s1||s2
    4. 基于
      like
      的模式匹配
      (1) % 描述任意str(0个或多个)
      (2) _ 描述单个char
      如:
      xx like ‘__O%’
      表示“ 第三个字符为O,且至少有三个字符长度的str
      (3) 对 _或% 表示用转义字符:
      xx like '30\%%'
      则,xx表示 30%开头的str

    c)three other oprs

    1. select *
    select * from r					//select all attrs in r
    select r1.* from r1,r2,...,rn	//select all attrs in ri
    1. oreder by
    order by attr1 desc, attr (asc), ...
    1. use predicate in
      where clause
    两个区间表示法:
    where SAL between 0 and 100
    where SAL not between 0 and 100
    
    n元组比较(字典序):			sqlserver中不支持
    select name, course_id
    from instructor, teaches
    where (instructor.ID, dept_name)=(teaches.ID, 'Biology')

    (5) Set Operations

    1. 参与两个的两个 set 模式要一致(参数数量相等,对应参数类型相容),否则报错(集合实际是表、关系)
    2. 集合运算结果自动去重,满足集合的数学特性
    3. three operations:
      union、intersect、except

    (6) NULL

    1. sql将涉及
      null
      的任何比较运算的outcome视为
      unknown
      ,而
      unknown
      作为和
      true、false
      并列的第三布尔值
    2. test for null attributes:
      is null、is not null
    3. select distinct
      查询时,对
      null
      的处理不同于谓词中
      null
      的比较
      (这里涉及了元组之间的比较运算,null=null返回不是unknown,而是true)

    (7) Aggregate Functions

    1. 聚集函数是以值的集合为input,返回单个值的函数
      有:
      avg, min, max, sum, count

      (
      !!!
      这里要注意 sum 和 count 的区别,从数据库里写sql String时容易混淆,bug生产机)

    a) basic aggregation

    如何区别如下三个语句?
    select count(distinct ID) from stu	计算有多少 ID不一样的 行数
    select count(ID) from stu	计算有多少 ID不为null 的行数
    select count(*)	from stu	计算关系中有多少行(即有多少tuple)

    聚合函数对null处理的principle:

    除了count(*)不忽略 集合中的null ,其他所有聚合函数都忽略 集合中的null

    b) aggregation with Grouping

    1. group by clause
      中所有属性上取值相同的元组将被分在一个组中
      依子句中的属性列表来分组,聚合函数的作用范围即为每个小组)
      (没有group by clause的实际是把整个table当成一个分组)
    2. 每个group只输出一个tuple,所以要保证 select attr 和 group by attr 的同步
      (select clause 中的 attribute 必须是 group by clause 中出现的,
      (否则就必须以聚合函数参数的形式出现

    c) ‘having’ clause

    1. having clause
      是在形成group之后才起作用,是对每个分组限制的子句
      (因此,在子句中发主要是使用几个聚合函数的谓词)
    2. having clause 也要与 group by clause 同步

    (8) Nested Sub-queries

    a) test for Set Membership

    测试单个attribute的成员资格
    attr in\not in set
    attr in\not in enum set(枚举类型)
    e.g. where name not in ('Mozart', 'Einstein')
    测试任意attribute的成员资格
    e.g. select count(distinct ID)
    from takes
    where (course_id, sec_id, semester, teach_year)
    in (select course_id, sec_id, semester, teach_year
    from teaches
    where teaches_id = 110)
    e.g. select dname
    from DEPT
    where deptno not in (select DEPTNO from EMP
    where DEPTNO is not null)--没有这行会有bug,null的影响!

    一句废话:where clause 和 join clause 均可实现 “过滤作用”

    b) Set Comparison

    >some(set)		至少比集合中的某一个要大	//=some() <=> in
    >all(set)		比集合中所有元素都大		//<>all() <=> not in
    
    e.g.找到工资高于30号部门某一个员工工资的 员工姓名编号
    select ename,sal
    from emp
    where sal> any(select sal from emp
    where deptno=30)

    c) test for Empty Relation

    1. true
      exists
      (subquery clause)
    2. true
      not exists
      (subquery clause)
    3. not exists(B except A)
      可以表示A包含B关系 ( B是A的子集 )
    Q:找出选修了biology系开设的所有课程的 学生
    select S.ID
    form student as S
    where not exists(
    (select course_id from course			--biology系开设的所有课程set
    where dept_name = 'biology')
    except
    (select T.course_id from takes as T	--相关子查询!
    where T.ID = S.ID)					--找出每个S.ID(学生)选修的课程set
    );

    d) test for Duplicate Tuples

    e) sub-query in ‘from’ clause

    select ...
    from (select ... from ... where...)
    as new_name_tuple(att1,att2,...,attn)
    where ...
    
    e.g. 找出所有系中工资总额最大的系:
    select max(tot_sal)
    from (select dept_name, sum(salary)
    from instructor
    group by dept_name) as dept_total(dname,tot_sal)

    f) ‘with’ clause

    with t1 as (
    query clause
    ), t2 as(
    query clause
    )...
    select ...	--在主语句中,t1 t2作为已知的表
    ...

    g) scalar query(标量子查询)

    1. 相关子查询(correlated sub-query)
      –运行机制:从外部查询开始,对外部查询的每一行,执行一遍内部查询。
      –可以把sub-query当作func(),只不过它的参数是外部查询每一行的某个信息
      –下面的例子既是:传入deptno,返回内部员工的数量cnt
    Q:找出 内部员工数量大于3 的所有部门
    select dname
    from dept
    where (select count(*) from emp		  这个子查询不能单独运行,
    where emp.deptno = dept.deptno)>3 因为dept.depto(来自外部)不在emp里
    1. 标量子查询(scalar sub-query)
      –sub-query return scalar value
      (thus a table having single attribute and single tuple)
      –func which returns single value
      (所以可以
      替代group by
      ,用在seclect clause内)
      (即对于外部传入的每一个属性,在内部找出满足这个outer attr的信息)
    Q:列出所有的系 + 他们拥有的教师数量
    select dept_name, (select count(*) from instructor
    where instrcutor.dept_name = department.dept_name
    ) as num_instructor
    对每一个dept_name(外部查询),只返回单个值!
    from department

    4. Modification operations

    (1) delete

    delete from r
    where P;			 删除r中满足谓词P的 某些行
    
    delete from r		 删除所有行(tuple),得到空关系
    
    drop table r		 删除整个表
    
    alter table r drop attri 删除一个属性 且 删除一纵列

    (2) insert

    (假设插入元组中不含有null,不考虑连接丢失问题 )

    insert into r
    values(att1, att2,..., attn)		--deprecated
    
    insert into r(att1, att2,..., attn)		--precated
    values(att1, att2,..., attn)	指定参数,排除database中各属性顺序的影响
    
    insert into r				向表中插入表!
    + sub-query clause
    e.g.
    insert into instructor
    select ID,name,dept_name
    from student
    where dept_name='music' and tot_ced>144;

    (3) update

    update r
    set attribute
    where ...		约束条件
    
    具体来看一个例子:
    (例子中显示了set部分用{key=value}键值对集合 的形式
    update stuDB
    set stuId='123',stuName='o',phoneNumber='o'
    ,qqNumber='o',eMail='o'
    where stuId = '20217';
    
    为避免更新顺序问题,可以使用 case clause(它可以出现在任何 该出现value的地方)
    e.g.
    update r
    set salary = case
    when salary>100 then salary*1.05
    when salary between 90 and 100 then salary*1.04
    ...
    else salary*1.00
    end

    5. Join Expression

    1. 连接条件
      : natural(share attrs)、using(A1,A2,…,An)、on(predicate)
    2. 连接类型
      : (inner) join、outer join(left、right、full)
      (外连接通过在outcome中创建null项的方式,保留了那些连接丢失的tuple)
      (因为不满足join…on…的条件而从结果中被自动舍弃)
    3. 类型可以和条件任意组合!(sql server 中不支持natural join and using)

    sql intermediate

    View (杂记)

    1. 区别基本表

      base table
      伪表

      (object of view 本身并不存储数据,只不过动态执行到view时,解析了view 所定义的语句罢了)

    2. create view
      name_xx
      as
      ( query expression )

      drop view
      name_xx

      insert into
      name_xx
      values
      (attr0,attr1,…)
      (插入一个新 tuple)

    3. 视图更新,是更新所查询的base table(改了库,慎重)

      Update
      name_xx
      Set
      (sequence)

    4. 视图 不可更新

      条件约束:

      create view
      xx
      as
      (sql query expression)
      with check option

    5. view + 权限 -> 解决数据安全问题

    example:
    grant select,update on user3.emp to user2 		对象权限(DML)
    grant create any table to user2					系统权限(DDL)
    revoke select on user3 .emp from user2 			回收权限

    some tools

    1. cast() # 进行数据类型转换
    2. isnull(a1,a2) # 判断a1是否为NULL,如果是返回a2 否则返回 a1
    3. top k ; row_number() #用于编号排序,并基于此 进行row提取
    • 点赞 4
    • 收藏
    • 分享
    • 文章举报
    Tonq_csdn 发布了5 篇原创文章 · 获赞 4 · 访问量 926 私信 关注
    内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
    标签: