mySQL CRUD操作(数据库的增删改查)

时间:2023-03-09 13:40:25
mySQL CRUD操作(数据库的增删改查)

一、数据库操作

1.创建数据库

create database 数据库名称

2.删除数据库

drop database 数据库名称

 

二、表操作

1.创建表

create table 表名

(

       列名类型(长度) 自增长非空主键,

)

**自增长:auto_increment

**主键:primary key

**非空:not null

**外键:foreign key 列名 references 表名(列名)

 

2.删除表

drop table 表名

3.修改表名

rename table 原表名 to 新表名;

 

三、数据库的CRUD操作(增删改查)

数据库里列称为字段,行称为“记录”;

 

1.插入记录(行)

insert into 表名 values(),值的数量要与列的数量一致;

2.插入字段(列)

insert into 表名(列名) values()

3.删除列

delete from 表名 where 条件(列名=值)

4.修改列名

update 表名 set 列名= where 条件

5.表的查询

普通查询:select * from 表名

特定查询:select 列名 from 表名

条件查询:select * from 表名 where 条件

多条件查询:select * from 表名 where 条件1 or 条件2or或的关系,and与的关系

关键字查询(模糊查询):select * from 表名 where 列名 like '%%',“%%”代表关键字在中间,“值%”代表关键字在前面,“%值”代表关键字在后面,“_”下划线代表任意一个字符;

范围查询:select * from 表名 where 列名 between A and B

离散查询:select * from 表名 where 列名 in(),在里面用in,不在里面用not in

分页查询:select * from 表名 limit n,m#分页查询,跳过n条数据(0)取几条

排序查询:select * from 表名 order by 列名 desc,默认为升序asc,降序为desc

分组查询:select * from 表名 group by 列名 having 条件,根据列名分组+筛选条件;

聚合函数查询:

①数量查询:select count(*) from 表名

②和值查询:select sum(列名) from 表名

③平均值查询:select avg(列名) from 表名

④最高值查询:select max(列名) from 表名

⑤最小值查询:select min(列名) from 表名

去重查询:select distinct 列名 from 表名

 

四、高级查询:

1.连接查询

select * from 1,2 where 连接条件

select * from 1 join 2 on 连接条件

笛卡尔积(例子)

select Info.code,Info.name,Info.sex,Nation.name as '民族',Info.birthday from Info,Nation where Info.nation=Nation.code

 

select * from Info join Nation on Info.nation=Nation.code

 

 

2.联合查询

select 列名,列名,列名 from 1     

union

select 列名,列名,列名 from 2

 

3.子查询

①无关子查询:子查询和父查询没有关系,子查询可以单独执行

select * from where =select from 表)

无关子查询---例子

查民族为'汉族'的所有学生信息

select * from Info where nation=(select code from nation where name='汉族')

 

查询生产厂商为'一汽大众'的所有汽车信息

select * from car where brand=()

select brand_code from brand where prod_code=()

select prod_code from productor where prod_name='一汽大众'

 

 

简化后的答案:select * from car where brand in(select brand_code from brand where prod_code=(select prod_code from productor where prod_name='一汽大众'))

 

②相关子查询:子查询和父查询存在互相的关系,子查询需要用到父查询的内容

 

 

相关子查询—---例子

 

查询汽车表中,汽车油耗小于该系列平均油耗的所有汽车信息

 

select * from car where oil<(该系列平均油耗)

select avg(oil) from car where brand =(该系列)

 

简化后的答案:select * from car a where oil<(select avg(oil) from car b where b.brand =a.brand)