SQL语句使用总结

创建数据库表,修饰关键字 primary key, not null, foreign key   references

create table Person(PName varchar(20),
    PAge int,
    PRemark varchar(20),
    primary key(PName));

插入数据

insert into Person(PName, PAge, PRemark) values("Jin", 18, "China")
insert into Person values("Li Chan", 23, "China")

查询所有数据

select * from Person

更改数据

update Person set PRemark="SuperMan"
update Person set PAge=30 where PName="Jin"

删除数据:删除Person表的全部数据,删除指定数据

delete from Person

delete from Person where PAge > 20 or PRemark = "Li Chan"

列表项取别名

select FNumber as Number1, FName as Name, FAge as Age from Emploee

数据汇总函数:最大值:MAX, 平均值:AVG, 求和:SUM, 最小值:MIN, 统计:COUNT(*)

select MAX(FSalary) from Employee where FAge > 25
select FDepartment, MIN(FAge) as FAgeMIN, MAX(FAge) as FAgeMAX, from Employee group by FDepartment

查询结果升级排序或降序排序

select * from Employee order by FAge ASC

select * from Employee order by FAge DESC

select * from Employee order by FAge DESC, FSalary DESC where FAge > 23

模糊查询,"__n_"匹配第三个字母为n的字符串,字符串长度为4;"T%" 匹配以"T"开头,长度任意的字符串

select * from Employee where FName like "_erry"

查询名字不为空的所有数据

select * from Employee where FName is not null

查询年龄不等于22岁,且工资不少于2000元的员工

select * from Employee where not(FAge=22) and not(FSalary<2000)

取出年龄是23岁,25岁,28岁的员工的数据

select FAge, FNumber, FName from Employee where FAge in(23, 25, 28)

取出年龄在23岁到27岁之间的员工数据

select * from Employee where FAge between 23 and 27

group by 子句的使用,group by 必须放到where语句之后;第二条select查询年龄只有一个人或三个人

select FAge from Employee where FName="Huang" group by FAge

select Fage, COUNT(*) as CountOfThisAge from Employee group by FAge having COUNT(*)=1 or COUNT(*)=3

 查询员工工资,按降序排序,取出第2到第5条数据

select * from Employee order by FSalary DESC limit 2, 5

特定查询

select top 3 * from Employee where FNumber not in (select top 5 FNumber from Employee order by FSalary DESC) order by FSalary DESC

DISTINCT 对整个结果集进行数据复抑制

select distinct FDepartment from Employee

计算字段可以在where 、update、delete中使用

select * from Employee where FSalary/(FAge - 21) > 1000

union all 显示重复行

union的使用原则

  • 每个结果集必须有相同的列数
  • 每个结果集的列必须类型相同
select FNumber, FName, FAge, FDepartment from Employee
union
select FCardNumber, FName, FAge, FAddress from TemEmployee

 

你可能感兴趣的:(SQL,SQL增删查改)