数据库(Database):按照数据结构来组织,存储,管理数据库的仓库。
关系型数据库管理系统(RDBMS)的特点:数据以表格的形式出现
每行为各种记录名称
每列为记录名称所对应的数据域
许多的行和列组成一张表单
若干的表单组成的database
RDBMS术语:数据库:数据库是一些关联表的集合
数据表:表示数据的矩阵
列:一列(数据元素)包含相同类型的数据
行:一行(元祖,记录)是一组相关的数据
冗余:存储两倍数据,冗余降低了性能,但提高了数据的安全性
主键:主键是唯一的,一个数据表只能有一个主键
外键:外键用于关联两个表
复合键:(组合键)将多个列为一个索引键,一般用于符合索引
索引:使用索引可快速访问数据表中的特定信息
参照完整性:参照的完整性要求关系中不允许引用不存在的实体。
登录本机的MySQL数据库:mysql -u root -p
创建数据库:create database 数据库名;
删除数据库:drop database 数据库名;
查看所有数据库:show databases;
选择数据库:use 数据库名;
创建表:crtate table 表名(列名,类型);
设置自增 auto_increment
设置非空 not null
设置主键 primary key
外键 FOREIGN KEY (字段名) REFERENCES 表名(字段名)
create table table_test(
table_id int primary key,
table_name varchar(10),
table_date date
);
删除表:drop table table_test;
清空表 :delete from 表名
truncate table 表名
修改表:添加列: alter table 表名 add 列名 类型
删除列:alter table 表名 drop column 列名
修改列: alter table 表名 modify column 列名 类型;
alter table 表名 change 原列名 新列名 类型;
添加主键: alter table 表名 add primary key(列名);
删除主键: alter table 表名 drop primary key;
插入数据:insert into 表名 (列名1 .. 列名n) values (value1 ... valuen)
insert into table_test(table_id,table_name,table_date)
values(1,"小明","2020-06-18")
查询数据:select 列名1,列名2 ...
from 表名
[where 查询条件] 条件表达式
[group by 列名] 列进行分类
[order by 列名] 列进行排序:升/降 DESC 降序 、 ASC 升序(默认)
[limit 数字] 返回的记录数
select * from table_test
select * from table_test where table_name="小兰"
select *
from table_test
where table_date="2020-06-18"
group by table_name
where 字句 关键字 binary :是区分大小写
select *
from table_test
where binary table_name="xiaoqian"
-- in关键字的查询
-- in(1,2,3...) 满足条件范围内的一个值即可
select *
from table_test
where table_test.table_name in ("小兰","小绿");
select *
from table_test
ORDER BY table_id desc
limit 4
查询指定记录
select *
from table_test
where table_id>3;
-- between and关键字的查询
-- BETWEEN...and... 在..到..范围内
select *
from table_test
where table_id between 1 and 4;
-- like 模糊查询 通配符"%"、"_"
-- % 作用是能匹配任意长度的字符
-- _ 只能匹配任意一个字符
select *
from table_test
where table_test.table_name like '小%';
select *
from table_test
where table_test.table_date like '2020-06-1_';
-- 匹配“2020-06-1”后面任意一个字符的日期
-- and 逻辑与
select *
from table_test
where table_id>2 and table_date<"2020-06-18";
-- 查询id大于2并且日期小于2020-6-18
-- or 逻辑或
select *
from table_test
where table_id>2 or table_date<"2020-06-18";
-- 查询id大于2或者日期小于2020-6-18
-- distinct 消除重复的值
select distinct table_date
from table_test;
-- count()计算有多少条记录
select table_name,count(table_date)
from table_test
-- count()函数 计算表中的函数
select count(*) from table_test;
-- sum()函数 返回列值得总和
select sum(table_num) from table_test;
-- avg()函数 求出指定数据的平均值
select avg(table_num) from table_test;
-- max()函数 返回该列的最大值
select max(table_num) from table_test;
-- min()函数 返回该列的最小值
select min(table_num) from table_test;
更新数据表:updata 表名 set 列名=新数值
[where 查询条件]
update table_test set table_num = table_num+1
-- 将所有的num数值加1
update table_test set table_num=56 where table_id=5
-- 修改id为5的num的数值
删除数据表:delete from 表名
[where 查询条件]
delete from table_test where table_id=3
-- 删除id为3的数据
delete from table_test
-- 删除表中所有数据