Mysql

Mysql基本操作

登陆数据库:

mysql -u root -p  

退出数据库:

exit;

数据库操作

创建数据库

create database 数据库名;
create database 数据库名 character set 字符集(utf8) collate 校对规则; 

删除数据库

drop database 数据库名;  

查看数据库

show databases -查看所有数据库
show create database 数据库名 -查看创建的数据库的信息

修改数据库

alter database 数据库名  

选中使用数据库

use 数据库名

表的操作

创建表

create table 表名{
    列名1 数据类型(长度)约束;
    列名2 数据类型(长度) 约束;
    ......
}

数据类型:
https://www.cnblogs.com/Caveolae/p/7058890.html
https://www.cnblogs.com/-xlp/p/8617760.html

约束:
主键:primary key (唯一,一个表只有一个主键)

第一种–单一主键:id int primary key(列级)
第二种–复合主键:primary key(id,name)设置多个主键(表级)
在主键中设置自增:id int primary key auto_increment

外键:foreign key (一个表可以有多个外键)

foreign key(外键) references 另一个表名(要关联的键)
给外键起名:constraint dpt_fk foreign key(外键名) conferences 表名(关联的键)

默认值:default

非空:not null

age int not null;

唯一约束:unique

第一种:email varchar(32) unique (列级)
第二种:unique(id,email) —组合约束 (表级)
第三种:constraint 约束名 unique(email) —约束起名字(表级)

操作表
表重命名:

rename table old to new;

删除表:

drop table 表名;

增加列:

alter table 表名 add 列名 数据类型 约束 after 列名;

可以指定新增列的位置

删除列:

alter table 表名 drop 列名;

修改列:

alter table 表名 modify 列名 数据类型 约束

改变表中数据

插入数据

insert into 表名(列1,列2,...) values(值1,值2...)
or
insert into 表名(列1,2...) values(值1,值2...),(v1,v2..),(v1,v2...)...

修改数据:

update 表名 set 列1=值1,列2=值2 where 条件

删除数据:

delete from 表名 where 条件

查询select语句

select * from 表名;
select 列1,列2,... from 表名;

select c1,c2,... from 表名 as 另一名;
select c1 as p1,c2 as p2,... from 表名;

select distinct c from 表名; ---去掉重复值

运算查询:
select *,列的运算 as 名 from 表名;

条件查询:
where 条件
select 查询内容 from 表名 where 条件
    关系运算符
    逻辑运算符
    模糊查询  like 
            where c like '条件'
            -:代表单个字符
            %:代表多个字符

    范围查询   in
            where c in (a1,a2,a3...)

排序查询:
order by c asc/desc
    asc:ascend 升序
    desc:descend 降序

聚合函数:
select sum(number) from 表名;
    sum()
    avg()
    count()
    max()
    min()

分组:
 group by

having:在group后,可以接聚合函数
where:在group之前,不可以接聚合函数

select ... from ... where ... group by ... having ... order by ...