目录

数据库

目录

数据库

MySQL数据库的基本操作

  • 创建数据库
create database 数据库名;
  • 查看数据库
show databases;
  • 使用数据库
use 数据库名;
  • 删除数据库
drop database 数据库名;
  • 创建表
create table 表名(
列名1 类型(长度) [约束]
列名2 类型(长度) [约束]
...
);

约束:

1、非空约束(NOT NULL)

2、默认值约束(DEFAULT)

3、唯一约束(UNIQUE)

4、主键约束(PRIMARY KEY)

  • 删除表
drop table 表名;
  • 修改列名
alter table 表名 change 列名 新列名 类型;
  • 修改列类型
alter table 表名 modify 列名 新类型;

查询

  • 查询表中全部信息
select * from 表名;
  • 查询表中指定列的信息
select 1,2 from 表名;
  • 数据去重
select distinct  from 表名;
  • 拼接结果
select concat(1,2) from 表名;
  • 条件查询
select  from 表名 where 条件;
  • 逻辑运算符(与:and/&&;或:or;非:not/!)
where 条件1 逻辑运算符 条件2;
where not 条件;
  • 范围查询
where  between 条件1 and 条件2;
where  not between 条件1 and 条件2;
where !( between 条件1 and 条件2);//不在这个区间
  • 集合查询
where  in(1,2);
where  not in(1,2);
  • NULL查询
where  is null;//查询列中值为NULL的数据
  • 模糊查询

    %:表示0到多个字符

    _:表示1个字符

where  like '%a';//表示以a结尾
where  like 'a%';//表示以开头
where  like '%a%';//表示数据中包含a

where  like '%a_';//数据倒数第二位是a
  • 结果排序
where 条件 order by  [asc/desc];//asc:升序,desc:降序
  • 聚合函数(count,max,min,sum,avg)
select 聚合函数 from 表名 [条件] group by  having 分组后的条件

语句执行顺序

from>where>group by>having>select>order by

where和having的区别:

where:先过滤已有的数据(数据是已经存在的),再进行分组,再聚合计算。

having:先分组,再对每组进行计算,根据得到的结果再过滤(分组把数据算出来之后,再过滤),使用having时,可以使用别名。

  • 多表查询(交叉连接,笛卡儿积)
select * from 1,2
  • 多表查询(内连接)
select * from 1,2 where 1.字段=2.字段;//隐式内连接,使用where条件消除笛卡儿积

select * from 1 inner join 2 on 1.字段=2.字段;//显示内连接
  • 多表查询(外连接:左外连接/右外连接/全外连接)
select * from 1 right/left join 2 on 1.字段==2.字段;//左外连接/右外连接

select 1.字段1,2.字段2 from 表名 as 1, 表名 as 2 where 1.字段1=2.字段2;
  • 子查询
select * from (select * from 表名) as 别名;

select * from where 条件->条件中包含查询语句;

插入

insert into 表名(字段1,字段2...) values(1,2,...);
insert into 表名(字段1,字段2) values(1,2),(3,4);//插入多条数据

insert into 表名 values(1,2);//针对全表所有字段插入操作

insert into 表名(字段) select 字段 from 2;//查询结果插入

insert into 表名 select 字段 from 2;//查询结果,全表插入

修改数据

update  set 字段= where 条件;//带条件修改指定数据,否则修改全表

删除数据

delete from  where 条件;//删除数据带条件指定数据,否则删除全表数据