一、对数据库的操作
1、创建一个数据库
普通创建>>> create database 数据库名;
创建特定编码格式>>>create database 数据库名 character set utf-8;
查看数据库的结构>>> show create database 数据库名;
查看所有数据库>>> show databases;
2、删除一个数据库
drop database 数据库名;
3、使用一个数据库
use 数据库名;
查看正在使用的数据库>>>select database();
二、对表的操作
1、创建一张表
create table 表名(
字段名 数据类型(长度) [约束],
字段名 数据类型(长度) [约束]
); 其中[]代表可选内容
单表约束:primary key 主键约束,要求字段唯一、非空
unique 唯一约束,要求字段唯一
not null 非空约束,要求字段非空
2、查看表
查看所有表>>>show tables;
查看表结构>>> desc 表名;
3、删除表
drop table if exists 表名;
4、修改表结构
添加一列>>>alter table 表名 add 列名 数据类型(长度) [约束];
修改一列>>>alter table 表名 modify 列名 数据类型(长度) [约束];
修改列名>>>alter tabke 表名 change 旧列名 新列名 数据类型(长度) [约束];
删除一列>>>alter table 表名 drop 列名;
修改表名>>> rename table 旧表名 to 新表名;
修改表的编码方式>>> alter table 表名 character set utf-8;
查看表编码方式>>>show create table 表名;
三、对表记录进行操作
1、插入数据
只插入某些列>>>insert into 表名(列名1,列名2,列名3...) values(值1,值2,值3....);
插入全部列>>>insert into 表名 values(值1,值2,值3...);
注意点:1、列名数要与值的数目相同
2、列的顺序与插入值的顺序相同
3、列的数据类型与插入值的类型相同
4、插入的值不能超过最大长度
5、插入的值如果是字符串或者日期要加''(一般是单引号)
2、更改数据
update 表名 set 字段名=值,字段名=值....;
update 表名 set 字段名=值, 字段名=值... where 条件;
注意点:1、列的数据类型与值相同
2、修改的值不能超过最大长度
3、如果是字符串或者日期要加单引号
3、删除表数据
删除所有>>> delete from 表名;
删除某个>>>delete from 表名 where 条件;或者truncate table 表名
区别:delete配合事务可恢复数据,id不重置;truncate会删除表再创建一张新表,数据不可恢复并且id重置
四、查询表数据
1、语法
select [distinct]* | 列名、列名 from 表名 [where 条件];
2、简单查询
1、查询所有商品
select * from product;
2、查询商品名和商品价格
select pname,price from product;
3、查询所有商品使用表别名
select * from product as p; as可省略
4、查询商品名使用列别名
select pname as product_name from product;
5、去掉重复值(按照价格)
select distinct(price) from product;
6、将所有商品价格+10进行显示
select price+10 from product;
3、条件查询
1、查询商品名为左慈的商品信息
select * from product where pname = '左慈';
2、查询商品价格大于60的所有商品信息
select * from product where price > 60;
3、查询商品名称中含有“士”的商品信息
select * from product where pname like '%士%';
select * from product where pname like '_士%';>>>一个下划线_表示一个占位符
4、查询商品id在(3,6,9)范围内的所有商品信息
select * from product where pid in (3,6,9);
5、查询id为2或者6的商品信息
select * from product where pid = 2 or pid =6;
4、排序
1、查询所有商品,按价格进行排序
select * from product order by price desc;>>>desc降序 asc升序
2、查询名称有“士”的商品并按价格降序排列
select * from product where pname like '%士%' order by price desc;
5、聚合(不统计null值)
1、获得所有商品的价格总和
select sum(price) from product ;
2、获得所有商品的平均价格
select avg(price) from product ;
3、获得商品的种类总数
select count(*) from product ;
6、分组
1、根据cid字段分组,分组后统计商品个数
select cid,count(*) from product group by cid;
2、根据cid分组,分组统计每组商品平均价格,并且平均价格大于20000元
select cid,avg(price) a from product group by cid having a>20000;
7、查询总结
select 一般在后面的内容都是要查询的字段
from 要查询的表
where 条件
group by 分组
having 分组后必须having而不用where
order by 排序。必须放到最后面
sum求和、avg平均、max最大值、min最小值、count数量