常用sql语句

创建数据库:create database menagerie

建表:create table pet (name varchar(20), owner varchar(20), species varchar(20), sex char(1), birth date, death date)

employee表
在这里插入图片描述
pet表
在这里插入图片描述
shop表
在这里插入图片描述

更新表中名字为Browser生日: update pet set birth = '1989-08-31' where name = 'Browser'

根据某字段排序:select name, species from pet order by birth desc

查询日期年、月、日:select Year('2018-02-05') as years from pet
Month()、Day()

过滤某个字段值最大的整条记录数据:select article, declear, price from pet where price = (select max(price) from shop)

每列最大值,根据某字段分组:select article, max(price) as price from shop group by article

聚合函数

count、sum、avg、max、min

count(1)、count()、count(列名)区别:
count(1)和count(
)执行结果同,查询包括null列数据
count(列名)查询不包括null列数据

执行效率上:
查询字段不为主键,count(1)>count(列名)>count(*)
查询字段为主键,count(列名)最优

内、左、右连接
select * from a inner(left|right) join b on a.A_ID=b.A_ID
in 和 exists
子查询记录少,主表较大,有索引:用in优
子查询表大,有索引,用exists优

select * from a where A_ID in(1,2,3)
select * from a where exists (select A_ID from b)
case sex
when '1' then '男'
when '2' then '女'
else '其他' end

select *, case when salary < 5000 then "低等收入"
when salary >= 5000 and salary < 10000 then "中等收入"
when salary > 10000 then "高等收入" end as level from employee
where 、group by、 having、 order by排序
select name, sum(*) from employee_tb1 where id <> 1 group by name having sum(*) > 5 order by sum(*) desc

删除、添加、修改表字段、字段类型、表名

alter table a drop
alter table a add i int
alter table a modify c char(10)
alter table a rename to b

常用函数

返回字符串s字符数:select char_length(s)
字符串s1、s2等多个字符串合并一个字符串:select concat(s1,s2) as s
返回第一个字符串s在字符串s1、s2中位置:select field(s1,s2)
返回字符串s的前n个字符:select left(s,n)
首尾去空格:trim(s)
从字符串s截取start位置处长度为length的字符串:select substring(s, start, length)

索引

创建索引:create index id on b(B_ID)
修改表添加索引:alter table b add index price(B_price)
删除索引:drop index price on b
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章