Mysql 入门
- 2021 年 8 月 24 日
- 筆記
Sql语言的分类–功能
-
DDL:用来创建或者删除数据库,表,数据库操作语句
-
DML:用来对表中的内容,进行增删改的,数据库中数据的操作语句
-
DQL:用来对表中的数据进行查询操作
-
DCL:权限管理语句
- database:数据库
-
table:表格(数据库的表)
- show:展示
DDL
创建数据库:
create database mydb1;– 创建数据库mydb1
删除数据库:
drop database mydb1; — 删除数据库mydb1
使用数据库:
use 数据库名称;
创建student表:
create table 表名(字段1 字段类型 约束,字段2 字段类型 约…….)
删除表:
drop table 表名;
修改表名称:
rename table 旧表名 to 新表名; –注意:如果有外键,需要更新外键
修改表结构
添加列:
alter table 表名 add 列名 类型
删除列:
alter table 表名 drop column 列名
修改列:
alter table 表名 modify 列名 类型; — 修改类型
alter table 表名 modify column 列名 类型; — 类型
alter table 表名 change 原列名 新列名 类型; — 列名,类型(可以改名字)
添加主键:
删除主键:
添加外键:
-- 附表创建 create table clazz(id int primary key ,clazz_name varchar(20)); -- 创建主表(带外键) create table student (id int primary key auto_increment,name varchar(20), clazz_id int ,foreign key (clazz_id) references clazz(id)); -- 删除外键 alter table -- 因为没有使用 constraint 关键字给外键起名 -- 所以student_ibfk_1(这是默认外键名) student drop foreign key student_ibfk_1; -- 增加外键 alter table student add -- 给外键起名clazz_id constraint clazz_id foreign key (clazz_id) references clazz(id);
删除外键:
修改默认值:
删除默认值:
DML
一、增
例: insert into tab1(name,email) values('zhangyanlin','[email protected]')
二、删
三、改
update 表 set name = ‘zhangyanlin’ where id>1 (一定要记得加条件,不让你就猴子他妈狒狒了!!)
DQL
四、查
select * from 表 select * from 表 where id > 1 select nid,name,gender as gg from 表 where id > 1
a、条件判断where
b、通配符like
c、限制limit
d、排序asc,desc
e、分组group by
select num from 表 group by num select num,nid from 表 group by num,nid select num,nid from 表 where nid > 10 group by num,nid order nid desc select num,nid,count(*),sum(score),max(score),min(score) from 表 group by num,nid select num from 表 group by num having max(id) > 10
特注意:group by 必须在where之后,order by之前