标签:
1.创建表
create table CeShi1
(
Uid varchar(50) primary key,
Pwd varchar(50),
Name varchar(50),
Nation varchar(50),
foreign key(Nation) references Nation(Code)
)
primary key 主键
not null 非空
foreign key(Nation) references Nation(Code) 外键
auto_increment 自增长
注意:所有符号必须是英文状态下的
每个表创建完之后加分号
表里面的最后一列写完之后不要加逗号
删除表:
drop table PinPai
数据的操作:CRUD操作
1.添加数据:
insert into Brand values(‘b001‘,‘宝马5‘); #第一种方式
insert into Brand (Code) values(‘b002‘);#第二种方式
insert into PinPai values(‘‘,‘大众‘); #处理自增长列
2.最简单查询
select * from PinPai #查询所有数据
select * from PinPai where Ids = 1;#根据条件查询
3.修改数据
update PinPai set Name = ‘大众‘ where Ids = 4; #修改某一条数据
update Car set Name=‘哈弗‘,Time=‘2012-3-4‘,Price=16,Brand=‘b002‘ where Code=‘c001‘
4.删除数据
delete from Brand #删除所有数据
delete from PinPai where Ids = 4; #根据条件删除数据
1.普通查询
select * from Info #查询所有内容
select Code,Name from Info #查询某几列
2.条件查询
select * from Info where Nation = ‘n001‘ #条件查询
select * from Info where Nation=‘n001‘ and Sex = true #条件之间并的关系
select * from Info where Sex = false or Nation = ‘n002‘ #条件之间或者的关系
3.模糊查询
select * from ChinaStates where AreaName like ‘中%‘ #查询以中开头的
select * from ChinaStates where AreaName like ‘%城%‘ #查询包含城的信息
select * from ChinaStates where AreaName like ‘_城%‘ #查询城在第二个位置出现的数据
4.排序查询
select * from Car order by Code desc #desc降序 asc 升序
select * from Car order by Brand
select * from Car order by Brand,Powers #按照两个列排序
5.统计查询(聚合函数)
select count(Code) from Car #查询总条数
select max(Price) from Car #查询最大值
select min(Price) from Car #查询最小值
select avg(Price) from Car #查询平均值
select sum(Price) from Car #查询总和
6.分组查询
select Code,Brand,count(*) from Car group by Brand #根据系列分组查看每组的数据条数
select * from Car group by Brand having count(*) >2 #查询分组之后数据条数大于2的
7.分页查询
select * from Car limit 5,5 #跳过几条数据取几条数据
8.去重查询
select distinct Nation from Info
高级查询
1.连接查询(对列的扩展)
第一种形式:
select * from Info,Nation #会形成笛卡尔积
select * from Info,Nation where Info.Nation = Nation.Code #加上筛选条件
select Info.Code,Info.Name,Sex,Nation.Name,Birthday from Info,Nation where Info.Nation = Nation.Code
#查询指定列
select Info.Code as ‘代号‘,Info.Name as ‘姓名‘,Sex as ‘性别‘,Nation.Name as ‘民族‘,Birthday as ‘生日‘ from Info,Nation where Info.Nation = Nation.Code #换表头
第二种形式:
select * from Info join Nation #join连接
select * from Info join Nation on Info.Nation = Nation.Code #join on关键字
2.联合查询(对行的扩展)
select * from Info where Nation = ‘n002‘
union
select * from Info where Code = ‘p002‘
3.子查询(无关子查询)
在一个SQL语句中,至少有两个查询,其中一个a查询的结果作为另一个b的查询条件,a成为里层查询或者子查询,
b成为外层查询或父查询。
查询民族为“汉族”的人员信息:
select * from Info where Nation =(select Code from Nation where Name = ‘汉族‘)
查询民族为“汉族”或者"回族"的人员信息
select * from Info where Nation in (select Code from Nation where Name = ‘汉族‘ or Name = ‘回族‘)
4.子查询(相关子查询)
查询同一系列的 油耗要比平均油耗低的汽车信息
子查询:select avg(Oil) from Car where Brand = ‘‘
父查询:select * from Car where Oil< 平均油耗
select * from Car a where a.Oil <(select avg(b.Oil) from Car b where b.Brand = a.Brand)
标签:
原文地址:http://www.cnblogs.com/xcc2016/p/5538874.html