9-25 钟申义 日志

常见关系型数据库

SQLit ; mysql ; sql server; Oracle

中文乱码

原因 :mysql 默认使用Latin-1编码
解决 :①,sql脚本文件另存为的编码为utf-8 ②,客户端连接服务器端使用的编码(set names utf-8);③服务器端创建的数据库使用编码(charset=utf-8)

MySQL常用的管理命令

查看数据库名 show databases
进入数据库 use 数据库名
查看表 show tables
查看表结构 desc 表名
退出链接 quit

SQL语法规范

1 每条命令以英文分号( ;)结尾,命令可跨行执行
2 一条命令出错后,这条命令及后面命令无法执行
3 sql不分大小写,习惯关键字用大写,非关键字用小写,上线后关键字小写可能造成错误
4 可注释

sql命令

DDL(定义数据)
create
创建 数据库 create database 数据库名 charset=utf8;
创建表 create table 表名(...);
drop
#丢弃数据库,如果数据库存在
drop database if exists 数据库名;
alter:修改数据库
DML(操作数据)
insert 插入数据 insert into 表名 values(...);
delet 删除数据 delete from 表名 where 数据(id=“1”)
update 修改数据 updat 表名 set 数据名=“ ”,数据名=“ ” where id=“”;
DQL(查询数据)
select 查询数据 select *(数据名)from 表名;
DCL(控制用户全限)
grant 授权
revoke 收回权限

数据类型

数值型
整型
tinyint 微整型 1字节 -128~127
smallint 小整型 2字节 -32768~32767
int 整型 4字节
bigint 大整型 8字节
浮点型
float 单精度浮点型 4字节
double 单精度浮点型 8字节
decimal(M,D):定点小数,不会产生计算误差,M代表总的有效位数,D代表小数点后的有效位数
布尔型 bool
日期型
date 日期型
time 时间型
datetime 日期时间型
字符串型
varchar(M)变长字符串 不会产生空间浪费,操作速度相对慢
char(M) 定长字符串 可能产生空间浪费,操作速度相对快
text(M) 大型变长字符串,M最多是2G

列约束

主键约束 parimary key auto_increment(自增长)
唯一约束 unique 不允许有重复的值可以为NULL NULL不与任何值相等包括自己
非空约束 not null 声明了非空约束的列上不允许插入NULL
检查约束 check mysql不支持
默认约束 default 设置默认值
外键约束 foreign key(列)references 表名+(主键列)

查询数据

简单查询
查询特定的列 select 数据名,数据名,... from 表名;
查询所有列 select * from 表名
给列起别名 select 数据名 as 别名,数据名 别名 from 表名
合并相同项 select distinct 数据名 from 表名
查询计算 select 数据名*12(计算) from 表名
查询结果排序 select *from 表名 order by 数据名 asc/desc 升序/降序
条件查询 select *from 表名 where 条件(salary>=500)
模糊查询 select *from 表名 where 数据名 like “%e-_”%表示很多字符,-(下划线)表示一个字符
分页查询 select *from 表名 limit m,n ;从m条开始查询n条
复杂查询
获取查询数量 select count(*) from 表名;
求总合 select sum(数据名) from 表名;
求平均数 select avg(数据名) from 表名 where 条件(sex=1);
求最大值,最小值 select max(salary) as 最高工资,min(salary) as 最低工资 from lfemp where sex=0;
年份 select year(birthday) from 表名;
月份 select month(birthday) from 表名;
分组查询 select avg(salary),max(salary),min(salary),sex from lfemp group by sex;
子查询 查询的条件是一个查询结果 select * from lfemp where salary>(select salary from lfemp where ename='tom');
多表查询(跨表查询)
内链接 inner join...on... select 数据名,数据名 from 表名 inner join 表名 on deptId=did(外键的两个);
左/右连接 left outer join .....on.... 查询左/右侧表中的所有数据 select ename,dname from lfemp left/right outer join lfdept on deptId=did(外键的两个);
全连接 左连接union右连接 (合并相同项)
左连接union all右连接 (不合并相同项)

心得

小程序还是满趣的,巩固复习了MySQL!

评论