1.连接本机数据库: mysql -uroot(用户名) -proot(密码)
2. 创建数据库: create database TestDb(数据库名称); <数据库名要区分大小写>
3.查看MySQL已存在的数据库: show databases;
4.使用数据库: use MyDb(数据库名称);
5.创建表: create table t_user( 内容<id int ,> ); 最后一个内容不加 ' , '
6.查看数据表的基本结构: desc 表名; —— describe 表名;
查看数据表的详细结构: show create table 表名 \G;<可以查看存储引擎和字符编码>
\G:改善排版。
7.定义主键 —— int id primary key , ---> 定义列时指定主键
—— primary key(id)<无 ,> --->定义完所有列后指定主键
—— primary key (name,id) --->>将几个字段联合起来作主键
8.删除表 : drop table 表名;
9.给表添加外部关键字: constraint 外键名 foreign key 字段名 references
主表名(主键名)
10.添加唯一约束: id int unique<唯一>
11.添加非空约束: id int not null
12.设置表的属性值自动增加:id int auto_increment <默认初始值和增量为1>
13.修改表名:alter table 旧表名 rename 新表名;
14.修改字段名:alter table 表名 change 旧字段名 新字段名 新数据类型;
15.修改字段名数据类型:alter table 表名 modify 字段名 数据类型;
16.添加字段:alter table 表名 add 新字段名 数据类型 [约束条件] [ first | after ] 已存在字段名;
17.在表的最后一列添加字段:alter table 表名 add 字段名 数据类型 ;
18.在表的第一添加字段:alter table 表名 add 字段名 数据类型 first;
19.在表的指定列后添加字段:alter table 表名 add 字段名 数据类型 after 字段名;
20. 删除字段:alter table 表名 drop 字段名;
21.修改字段排列位置:alter table 表名 modify 字段1 <要修改未知的字段> 数据类型 first | ( after 字段2);
22.修改字段到表的指定列后:alter table 表名 modify 字段名 数据类型 after 字段名;
23.删除表的外键约束:alter table 表名 drop foreign key 外键约束名;
24.为表的所有字段插入数据:insert into 表名(字段名<可以有多个>) values (内容);
25.为表中指定字段插入数据:insert into 表名(字段名) values(内容),(内容),(内容);
26. 更新表中指定的内容:update 表名 set 字段名1 = 内容1,字段名2 = 内容2 where 过滤条件;
27.删除表中的指定行:delete from 表名 where 条件语句<和过滤条件类似>;
28.删除表中所有行:delete from 表名;
truncate table 表名; ——直接删除表,删除结束后会重新建一个表;速度比delete快
29.Betweed and 查询:select 字段名 from 表名 where 字段名 (NOT) betweed <范围开始值> and <结束值>;
30.使用通配符 % 可以匹配任意长度的字符(包括零字符):select 字段名 from 表名 where 字段名 like '字符%'<查询字符开头> ('%字符%')<字符在中间> ('%字符')<字符结尾>;
31.使用通配符_模糊匹配数据内容:select 字段名 from where 字段名 like '字符_';(和%部分用法类似) 注:一个'_'模糊匹配一个字符;
32.查询空值:select 字段名 from 表名 where 字段名 is (NOT) null;
33.去除重复结果:select distinct 字段名 from 表名;
34.带and关键字的多条件查询:select 字段名 from 表名 where 表达式1 and 表达式2;
35.带or关键字的多条件查询:select 字段名 from 表名 where 表达式1 or 表达式2;
注:or 和 and 可以一起使用,and 优先于 or;
36.带in关键字的多条件查询:select 字段名 from 表名 where 字段名 in( 表达式1 , 表达式2); <优先使用>
37.对查询结果排序:select 字段名 from 表名 order by 字段名 asc\desc;
38.分组查询的单独使用:select 字段名 from 表名 group by 字段名;
39.limit 的使用:select 字段名 from 表名 limit [offset ,] 记录数;注:offset为偏移量,默认为0,表示从表的第一条记录开始查询; 记录数:返回查询结果的条数
40.内连接查询:select (表名1 . 字段名 ,表2 . 字段名)<连接的表,也就是打印出来的表> from 表2 inner join 表1 on (表1 . 字段 = 表2 . 字段)<连接条件>;
注:<表名 as 新表名 > as:可给表或列起别名
41.外连接查询:
注释:
常用约束:1. not null 约束:确保某列不能有null值
2. default 约束: 当某列没有指定值时,为该列提供默认值
3. unique 约束:确保某列中的值是不同的
4. primary key 约束:唯一标识数据库中的各行/各列
5. check 约束:check 约束确保某列中的所有值满足一定条件。