zoukankan      html  css  js  c++  java
  • 主键 子查询

    一、主键 primary key

     1 create database dudu
     2 go
     3 use dudu
     4 go 
     5 create table bumen
     6 (
     7    bcode int primary key,  --部门编号--bcode为主键,不能重复,确保唯一性
     8    bname varchar(20),  --部门名字
     9    bzhuguan varchar(20),  --部门主管
    10 )
    11 create table renyuan
    12 (
    13 code int primary key identity(1001,1),   --人员编号 --code为主键,不能重复,确保唯一性。identity(1001,1)自增长主键,表示从1001开始,每次增加1,当添加元素时,不用添加此列
    14 name varchar(20),  --人员名字
    15 age int,  --人员年龄
    16 bc int   --人员所属部门编号
    17 )

    二、子查询(尽可能的用主键作为查询条件

    从上面两表(renyuan和bumen)得知,bc和bcode是一样的,可以根据这个条件来设置关系,即设置外键

    设置好外键后,添加元素:

    1 insert into bumen values(101,'财务部','张三')
    2 insert into bumen values(102,'销售部','李四')
    3 insert into bumen values(103,'技术部','王五')
    4 go
    5 insert into renshu values('张三',34,101)
    6 insert into renshu values('李四',35,102)
    7 insert into renshu values('王五',24,103)
    8 insert into renshu values('白居易',33,101)
    9 insert into renshu values('李清照',45,102)
    10 insert into renshu values('王阳明',27,103)
    11 insert into renshu values('孔子',78,101)
    12 insert into renshu values('孟子','66,102)
    13 insert into renshu values('老子',89,103)

    注意:在给renyuan添加时没有加入code,是因为前面有identity(1001,1)。

    -查询年纪最大的人的部门名称
    select bname from bumen where bcode=
    (select bc from renyuan where code=
    (select code from renyuan where age=
    (select MAX(age) from renyuan)))
    --查询销售部里的年龄大于35岁的人的所有信息
    select * from renyuan where code in (select code from renyuan where age>35)  and select bc from bumen where baname='销售部'
    --按照年龄排序后的前三个人的所有信息
    select top 3 * from renyuan order by age
    
    --按照年龄排序后的6/7/8名人员的所有信息
    select top 3 * from renyuan where code not in (select top 5 code from renyuan order by age) order by age

            

    --查看所有人员信息,将部门编号替代为部门名称
    select code,name,age,(select bname from bumen where bumen.bname=renyuan,bc) as 部门 from renyuan

    完!!

  • 相关阅读:
    MySql存储过程—2、第一个MySql存储过程的建立
    MYSQL 存储过程1、SQL存储过程的基础知识
    [转]忍无可忍 献上一曲维族歌曲 《我们的客户是花园》(吐槽)
    由硬盘供电不稳、数据线品质差造成的蓝屏
    music Elton John
    一个人在艰苦中能雄起,那是能力和毅力,一个人在安逸中能雄起,那是自觉和自律。
    安装VS2012出问题后,反复重启电脑。
    山寨、低端、劣质的机箱前置面板的悲剧。
    SQL Server Management Studio (SSMS) 清除登录记录
    DataTable 分批处理,每批处理4行
  • 原文地址:https://www.cnblogs.com/wwz-wwz/p/5831712.html
Copyright © 2011-2022 走看看