数据库


create table CeShi1
(
Uid varchar(50) primary key,
Pwd varchar(50),
Name varchar(50),
Nation varchar(50),
foreign key(Nation) references Nation(code)
)

写查询语句需要注意
1、创建表的时候,最后一列后面不要写逗号
2、如果有多条语句一起执行,注意语句之间加分号分隔
3、写代码所有符号都是半角的

关系型数据库:表和表之间是有关系存在的

创建表的几个关键字:
1、主键:primary key
2、非空:not null
3、自增长列:auto_increnment
4、外键关系:foreign key(列名) references 表名(列名)

CRLD操作

1、添加数据:
insert into Info values('','','','','')要求values括号里面的值的个数要和表里面列数相同
insert into Info (Code,Name) values('','')添加指定列的值

2、修改数据:
updata Info set Name='张三' where Code ='p001'

3、删除数据:
delete from Info Code ='p001'

查询数据:

1.普通查询,查所有的
select * from Info #查所有数据
select Code,Name from Info #查指定列

2.条件查询
select * from Info where Code ='p001' #一个条件
select * from Info where Name ='张三' and Nation='n001' #两个条件并的关系
select * from Info where Name ='张三' or Nation='n001' #两个条件或的关系

3.排序查询
select * from Info order by Birthday #默认升序排列asc 如果要降序排列 desc
select * from Car order by Brand,oil desc #多列排序

4.聚合函数
select count(*) from Info #取个数
select sum(Price) from Car #查询price列的和
select avg(Price) from Car #查询price列的平均值
select max(Price) from Car #查询price列的最大值
select min(Price) from Car #查询price列的最小值

5.分页查询
select * from Car limit n,m #跳过n条数据取m条数据

6.分组查询
select Brand from Car group by Brand #简单分组查询
select Brand from Car group by Brand having count(*)>2 #查询系列里面车的数量大于2的系列

7.去重查询
select distinct Brand from Car

8.修改域名
select Brand as '系列' from Car

9.模糊查询
select * from Car where Name like '_迪%' %代表多个字符 _代表一个字符

10.离散查询
select * from Car where Code in ('c001','c002','c003','c004')
select * from Car where Code not in ('c001','c002','c003','c004')


高级查询

1、链接查询

select * from Info,Nation #得出的结果称为迪卡尔积
select * from Info,Nation where Info.Nation=Nation.code

join on链接

select * from Info join Nation #join链接 结果为笛卡尔积
select * from Info join Nation on Info.Nation =Nation.code

2、联合查询

select Code,Name from Info
union
select Code,Name from Nation

3、子查询

(1)无关子查询
select Code from Nation where Name = '汉族' #去Nation表中查询汉族的民族代号

select * from Info where Nation = (民族代号) #在Info表中查询民族代号为上一个查询结果的所有信息

select * from Info where Nation = (select code from Nation where Name ='汉族')

子查询查询的结果被父查询使用,子查询可以单独执行的称为无关子查询


(2)相关子查询

select * from Car where Oil<(改系列的平均油耗) #查询油耗小于该系列平均油耗
select avg(Oil) from Car where Brand = '值' #查询某系列的平均油耗

select * from Car a where Oil<(select avg(Oil) from Car b where b.Brand = 'a.Brand' )

原文地址:https://www.cnblogs.com/banyue5026/p/5483361.html