SQL 随笔(Ⅱ)。。。

今天记记 去重、排序、子查询、外键

先做个表,练习下手感

create  table LOL
(
code int primary key  identity(1,1),
name varchar(50) not null,
sex varchar(50) not null,
age int  not null,
sg  int  not null,
wuqi varchar(50)not null,
dizhi varchar(max)not null,

)

insert into LOL values(。。。。。。。) -------如下截图
select*from LOL

select top 3 name,code from LOL where age>=20 select distinct  name from LOL  -------------去重--distinct

select*from LOL order by age asc---升序    --------order by 排序

select*from LOL  order by age desc---降序

select*from LOL where kg<70 order by kg

select*from LOL order by age asc,cm , kg desc ------再不改变第一组排序结果基础上,再排第二次序是排不出来的

-----分组group by列,对那一列进行分组,就只能显示哪一列

select name  fromLOL group by name---对某一列分组,相当于去重显示

--------运算符查询年龄加5岁之后大于23的

select*from LOL where age+5>23

--算数运算符:+-*/%

--比较运算符:> < >= <= !=  !<  !>

--逻辑运算符:ang or   ------or或者

--all any some in not -------all所有的意思,结合一个范围来使用 --in  在什么参数范围之内

select*from LOL where age  in(20,21) --相当于 age=20  or age=21

select*from LOL where age  not in(20,21)

--------查询年龄不在身高是180的人的年龄范围之内的信息

select*from LOL where   cm=180 select*from LOL where  age!=22

--子查询:就是使用查询语句查询一列数据出来,然后作为其他查询的查询条件中的参数来使用

--查询身高不在年龄是22岁的人的身高范围之内的

select*from LOL where age=22---注意是一列信息作为参数

select*from LOL where cm not in (select cm from LOL where age=22)

--名字叫盖伦的人中年龄比code=1的约里克那个人的年龄大三岁的人的信息是

select*from LOL where age-3=(select age from LOL where code=3)and name='盖伦'

--查询年龄不在身高是180的,并且年龄是超过25的范围之内的信息
select*from LOL where age  not in(select age from LOL where sg=180)and (age>25)
--查询来自德玛西亚的,年龄小于22或者身高小于170
select*from LOL where dizhi='德玛西亚'and(age<22  or sg<170)

--外键:受约束的表叫外键表,约束的数据源叫主键表

--要想加外键,首先的有主键表

--要想删主键表数据,必须先删除外键表数据

--作为外键的数据源的列,必须要是一个唯一键(这一列必须是主键或者是unique)

create table teacher

(

tno int primary key identity(1,1) not null,

tname varchar(50)

) ----------------------------------------- 主键表

go

create table student

(

sno int primary key identity(1,1),

sname varchar(50),

tno int references teacher(tno),

cid varchar(20)unique

) ------------------------------------------外键表

insert into student()

原文地址:https://www.cnblogs.com/qiaoyifan3111/p/4442929.html