day02-MySQL

发布时间 2023-12-21 10:20:22作者: 白子伍

数据库-MySQL

1. 数据库基础操作

  • mysql -u用户名 -p密码 [-h数据库服务器的IP地址 -P端口号]

    -h 参数不加,默认连接的是本地 127.0.0.1 的MySQL服务器,-P参数不加,默认连接的端口号是 3306
    eg. mysql -uroot -p1234

  • 查询所有数据库

    show databases;

  • 创建数据库

    create database [ if not exists ] 数据库名

  • 使用和删除数据库

    use 数据库名;
    drop database [ if exists ] 数据库名 ;

2. 表基础操作

2.1. 创建表

create table 表名(
字段1 字段1类型 [约束] [comment 字段1注释 ],
字段2 字段2类型 [约束] [comment 字段2注释 ],
......
字段n 字段n类型 [约束] [comment 字段n注释 ]
) [ comment 表注释 ] ;

eg:
    create table tb_user (
    id int primary key auto_increment comment 'ID,唯一标识', #主键自动增长
    username varchar(20) not null unique comment '用户名',
    name varchar(10) not null comment '姓名',
    age int comment '年龄',
    gender char(1) default '男' comment '性别'
    ) comment '用户表';

2.2. 修改表

  • alter table 表名 add 字段名 类型(长度) [comment 注释] [约束];
  • alter table 表名 modify 字段名 新数据类型(长度);
  • alter table 表名 change 旧字段名 新字段名 类型(长度) [comment 注释] [约束];
  • rename table 表名 to 新表名;
eg.
    alter table tb_emp add qq varchar(11) comment 'QQ号码';
    alter table tb_emp modify qq varchar(13) comment 'QQ号码';
    alter table tb_emp change qq qq_num varchar(13) comment 'QQ号码';
    rename table tb_emp to emp;

2.3. 删除字段

alter table 表名 drop 字段名;

alter table tb_emp drop qq_num;

3. 数据库操作

  • 批量添加数据(指定字段)

insert into 表名 (字段名1, 字段名2) values (值1, 值2), (值1, 值2);

  • 批量添加数据(全部字段)

insert into 表名 values (值1, 值2, ...), (值1, 值2, ...);

  • update语法

update 表名 set 字段名1 = 值1 , 字段名2 = 值2 , .... [where 条件] ;

  • delete语法:

delete from 表名 [where 条件] ;

  • 查询操作

select 字段列表 from 表名列表
where 条件列表 group by 分组字段列表 having 分组后条件列表
order by 排序字段列表 limit 分页参数(起始索引, 查询记录数)

案例:查询入职时间在 '2015-01-01' (包含) 以前的员工 , 并对结果根据职位分组 , 获取员工数量大于等
于2的职位

select job, count(*)
from tb_emp
where entrydate <= '2015-01-01' -- 分组前条件
group by job -- 按照job字段分组
having count(*) >= 2; -- 分组后条件

where与having区别(面试题)

  • 执行时机不同:where是分组之前进行过滤,不满足where条件,不参与分组;而having是分组之
    后对结果进行过滤
    -判断条件不同:where不能对聚合函数进行判断,而having可以。

4. 多表查询

多表查询可以分为:

  1. 连接查询

    • 内连接:相当于查询A、B交集部分数据
  2. 外连接

    • 左外连接:查询左表所有数据(包括两张表交集部分数据)

    • 右外连接:查询右表所有数据(包括两张表交集部分数据)

  3. 子查询

  • 内连接

select 字段列表 from 表1 , 表2 where 条件 ... ;

  • 左外连接

select 字段列表 from 表1 left join 表2 on 连接条件 ... ;

  • 右外连接

select 字段列表 from 表1 right join 表2 on 连接条件 ... ;

事务

四大特性

事务有哪些特性?

  • 原子性(Atomicity):事务是不可分割的最小单元,要么全部成功,要么全部失败。
  • 一致性(Consistency):事务完成时,必须使所有的数据都保持一致状态。
  • 隔离性(Isolation):数据库系统提供的隔离机制,保证事务在不受外部并发操作影响的独立环境
    下运行。
  • 持久性(Durability):事务一旦提交或回滚,它对数据库中的数据的改变就是永久的。

索引

作用:提高查询的效率。
缺点:索引会占用存储空间。索引大大提高了查询效率,但是同时也降低了insert,update,delete的效率

  • 添加索引

    create index idx_sku_sn on tb_sku (sn); #在添加索引时,也需要消耗时间

MySQL数据库支持的索引结构有很多,如:Hash索引、B+Tree索引、Full-Text索引等。
我们平常所说的索引,如果没有特别指明,都是指默认的 B+Tree 结构组织的索引。