MySQL基础知识1

2022/1/3 19:07:18

本文主要是介绍MySQL基础知识1,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

数据库

创建数据库
create database 数据库名称;

查看数据库
show databases;

查看已经建好的数据库
show create database 数据库名;

修改数据库
编码方式
alter database 数据库名称 default character set 编码方式== collate== 编码方式_bin

删除数据库
drop database 数据库名;

数据表

建表
create table 表名{
字段名1,数据类型[完整性约束条件],
字段名2,数据类型[完整性约束条件],
}

查表
show tables;

查看数据表的字符编码和定义语句
show create table 表名;
describe 表名;/desc 表名;查看字段名
\G在语句最后添加,使结果整齐美观

修改数据表
alter table 旧表名 rename to 新表名;

修改表字段名
alter table 表名 change 旧字段名 新字段名 新数据类型;

修改字段的数据类型
alter table 表名 modify 字段名 数据类型;

添加字段
alter table 表名 add 新字段名 数据类型【约束条件】【first|after已存在字段名】
first,after为可选参数

删除字段
alter table 表名 drop 字段名

修改字段的排列位置
alter table 表名 modify 字段名1 first|after 字段名2 ;

删除数据表
drop table 表名;

向表中添加数据
insert into 表名(字段名1,字段名2,…)values(值1,值2,…)
另外的方法:
insert into 表名set 字段名1=值1 ,【字段名2=值2…】
如果不指定字段名,值的顺序必须要和字段在表中定义顺序相同

查询表
select * from 表名;

更新数据
update 表名 set 字段名1=值1,[字段名2=值2,…][where 条件表达式]
更新全部数据
update 表名 set 字段名=值

删除数据
delete from 表名[where 条件表达式]
删除全部数据
1.delete from 表名;
2.truncate table 表名;

单表查询

in关键字查询
select * [字段名1,字段名2,…] from 表名 where 字段名 not|in (元素1,元素2,…)

between。。and
select * [字段名1,字段名2,…] from 表名 where 字段名 between 元素1 and 元素2

空值查询
select * [字段名1,字段名2,…] from 表名 where 字段名
==is ==[not] null

distinct:过滤重复值
select distinct 字段名 from 表名

like:模糊查询
select * [字段名1,字段名2,…] from 表名 where 字段名
[not ] like ‘匹配字符串’;
% 匹配任意长度字符串,包括空字符串
_匹配一个字符串
\转义字符

and多条件查询,全部满足条件
or满足一个条件就会被查询出来
count()返回某列的行数:select count(*)from 表名
sum()返回某列的和:select sum(字段名)from 表名
avg()返回某列的平均值:select avg (字段名)from 表名
Max()返回某列最大值
min()返回某列最小值

order by 排序使用了asc ,desc关键字
select * from 表名 order by 字段名 [asc|desc]

group by 。。having 分组查询
select 字段名1,字段名2 from 表名 group by 字段名1,字段名2…[having 条件表达式]

limit限制查询结果的数量
select *from 表名 limit 数量;

as为表和字段取别名
select *from 表名as别名;

查询语句
格式
select 列名 * form 表名 where 查询条件 and/or 查询条件2 group by 列 having 分组条件 order by 排序

多表操作

外键
外键是引用另一个表中的一列或多列,用于加强两个表数据之间的连接

操作关联表

交叉连接:将两个表的数据组合在一起
select * from 表1 cross join 表2;

内连接:
又称简单连接或自然连接,使用比较运算符对两个表中数据进行比较,并列出与连接条件匹配的数据行。
select 查询字段 from 表1 [inner] join 表2 on 表1.关系字段=表2.关系字段
也可以使用where

外连接:左连接,右连接
语法:
select 所查字段 from表1 left|right|outerjoin 表2 on 表1.关系字段=表2.关系字段 where 条件
左连接
左表中所有记录和右表中符合连接条件的记录
右连接
右表中所有记录和左表中符合连接条件的记录

表的约束
primary key 主键约束,用于唯一标识对应记录
foreign key 外键约束
not Null 非空约束
==unique == 唯一性约束
==default == 默认值约束,用于设置字段的默认值

单字段主键
字段名 数据类型 primary key
多字段主键
primary key( 字段名1,字段名2,字段名3)
例如
create table student(
stu_id int auto_increment,
grade float,
primary key(stu_id ,grade)
);

auto_increment 字段自动增加

unique 唯一性索引
fulltext 全文索引
spatial 空间索引
index 指名字段为索引

在已存在的表上创建索引
create index 索引名 on 表名 (字段名[(长度)] [asc|desc])
例如:
在book表中bookid字段上创建一个名为index_id的索引
create index index_id on book(bookid)

使用alter table语句在已知的表上创建索引
alter table 表名 add [unique|fulletext|spatial] index 索引名(字段名【长度】[asc|desc])

删除索引
drop index 索引名 on 表名



这篇关于MySQL基础知识1的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程