目录
sql基本使用方法
注意事项
- sql语句不区分大小写
- 各条sql语句用";"分号断句
数据操作语句(DML)
select查询语句
select 列名 from 表名 where 条件语句;
注意:
- 显示全部列可以用*表示
select * from 表名;
- 返回列中不重复的值,
select DISTINCT 列名 from 表名;
- where条件语句
select 列名 from 表名 where 列名 运算符 限定条件的内容
//下面为查找user表中name为LiMing的数据
//* 表示满足条件的全部列
// "LiMing"表示name类型为字符串
select * from user where name="LiMing";
//查询Year大于1965
select * from user where year>2022;
//错误演示:因为year类型为int如果写成year>"2022"则错误
select * from user where yera>"2022";
运算符:
- 逻辑运算符
=等于
<>不等于
>大于
<小于
>=大于等于
<=小于等于
- between&like范围运算符
between 某个范围
//例如
like 某种模式
//例如查询不包含Li以外的数据
select * from user where name not like '%Li%'
- and&or多条件连接运算符
and 表示where后的全部条件表达式均满足条件则where整体状态为满足条件
or 表示where后的全部条件表达式有一个满足条件则where整体状态为满足条件
//查询user表中满足name="Yibo"并且year=2022的记录
select * from user where name="Yibo" and year=2022;
//查询user表中满足name="Yibo"或者year=2022或者两个条件都满足的记录
select * from user where name="Yibo" or year=2022;
order by 排序语句
基本常识:
- ASC 顺序排序(默认)
- DESC 倒序排序
例子:
//1 将user表中的记录按照score列值顺序排序
select * from user order by score
//2 将user表中的记录先按照name中的字母倒叙排序,如果字母相同再按score顺序排序
select * from user order by name DESC,score ASC
//3 将user表中的记录按照score列值从小到大倒叙排序
select * from user order by score DESC
update更新语句
update 表名 set 列名=新值 where 条件语句
update user set name="XiaoMing" where name="LiMing"
delect 删除语句
delect from 表名 where 表达式
delect from user where name="XiaoMing"
//小技巧:删除全部数据保留数据表结构
delect * from user
//删除响应表中满足表达式的数据
insert into 添加语句
insert into 表名 (列名1,列名2,列名3...) values (值1,值2,值3...)
//
insert into user (name,year) values ("Bob",2019);
数据定义语句(DDL)
create 创建
//创建一个admin表,包括id,name,password列
creat table admin(
id int,
name varchar(255),
password varchar(255)
)
alter 修改
在user表中添加age列并且类型为int
alter table user add age int;
使用alter删除user表中year列
alter table user drop column year;
drop 删除
删除指定表中数据内容,保留数据表结构
truncate table 表名
完全删除表,结构+数据都删除
drop table 表名
//完全删除user表
drop table user
完全删除数据库
drop database 数据库名
drop database student
常用函数
三角函数
- sin()
- cos()
绝对值函数
- abs()
select abs(-1)
//返回值为1
查询字符串长度包含空格
- length()
select length("1 23")
//返回值为4
大小写字母转换