MySQL基础回顾
1、数据库概念
数据库
数据库软件
数据仓库
- 数据量更加庞大,更加侧重数据分析和数据挖掘,供企业决策分析之用,主要是数据查询,修改和删除很少
2、MySQL的特点
- 关系型数据库
- 跨平台
- 支持多种编程语言(python、java、php)
- 基于磁盘存储,数据是以文件形式存放在数据库目录/var/lib/mysql下
3、启动连接
sudo /etc/init.d/mysql start|stop|restart|status
sudo service mysql start|stop|restart|status
mysql -hIP地址 -u用户名 -p密码
本地连接可省略 -h 选项
4、基本SQL命令
库管理
1、查看已有库;show databases;
2、创建库并指定字符集;create database 库名 [charset utf8];
3、查看当前所在库;select database();
4、切换库;use 库名;
5、查看库中已有表;show tables;
6、删除库;drop database 库名;
表管理
1、创建表并指定字符集;create table 表名(字段名 数据类型)[charset=utf8];
2、查看创建表的语句 (字符集、存储引擎);show create table 表名;
3、查看表结构;desc 表名;
4、删除表;drop table 表名1,表名2;
表记录管理
1、增 :insert into 表名 values(记录1),(记录2);
insert into 表名(字段1,...) values(值1),...;
2、删 :delete from 表名 where 条件;
3、改 :update 表名 set 字段名=值,字段名=值 where 条件;
4、查 :select 字段名1,字段名2 from 表名 where 条件;
表字段管理
1、增 :alter table 表名 add 字段名 类型 [添加位置first|after 字段名];
2、删 :alter table 表名 drop 字段名;
3、改 :alter table 表名 modify 字段名 新类型;
4、表重命名 :alter table 表名 rename 新表名;
5、数据类型
四大数据类型
int smallint bigint tinyint
float(m,n) double decimal
char() varchar() text longtext blob longblob
enum() set()
date time year datetime timestamp
日期时间函数
now() curdate() curtime() year(字段名) date(字段名) time(字段名)
日期时间运算
select * from 表名 where 字段名 运算符(now()-interval 间隔); (间隔:1 year|3 month|5 day)
eg:查询3天内的记录
select * from tab where time >(now()-interval 3 day);
6、MySQL运算符
> >= < <= = !=
eg1 : 查询成绩不及格的学生
select stu from tabstu where score<60;
eg2 : 删除成绩不及格的学生
delete from tabstu where score<60;
eg3 : 把id为3的学生的姓名改为 周芷若
update tabstu set name="周姑娘" where id=3;
and or
eg1 : 查询成绩不及格的男生
select * from tabstu where score<60 and sex="男";
eg2 : 查询成绩在60-70之间的学生
select * from tabstu where score>60 and score<70;
between 值1 and 值2 、in() 、not in()
eg1 : 查询不及格的学生姓名及成绩
select name,score from tabstu where score between 0 and 59;
eg2 : 查询AID1903和AID1902班的学生姓名及成绩
select name,score from tabstu where class in('AID1902','AID1903')
where 字段名 like 表达式(%_)
eg1 : 查询北京的姓赵的学生信息
select * from tabstu where address='北京' and name like '赵%';
is NULL 、is not NULL
eg1 : 查询姓名字段值为NULL的学生信息
select * from tabstu where name is NULL;
7、查询
给查询的结果进行排序(永远放在SQL命令的倒数第二的位置写)
order by 字段名 ASC(升序)/DESC(降序)
eg1 : 查询成绩从高到低排列
select * from tabstu order by score desc;
限制显示查询记录的条数(永远放在SQL命令的最后写)
limit n :显示前n条
limit m,n :从第(m+1)条记录开始,显示n条
分页:每页显示10条,显示第6页的内容
limit 50,10
MySQL高级-Day01
MySQL基础巩固
- 创建库 :country(指定字符编码为utf8)
-
创建表 :sanguo 字段:id 、name、attack、defense、gender、country
要求 :id设置为主键,并设置自增长属性
- 插入5条表记录(id 1-5,name-诸葛亮、司马懿、貂蝉、张飞、赵云),攻击>100,防御<100)
- 查找所有蜀国人的信息
- 将赵云的攻击力设置为360,防御力设置为68
update sanguo set attack=360,defense=68 where name='赵云';
- 将吴国英雄中攻击值为110的英雄的攻击值改为100,防