1.登录MySQL
- 在命令行中登录MySQL
mysql -uroot -proot
2.数据库的基本操作
- 创建数据库
create database 数据库名字;
- 删除数据库
drop database 数据库名字;
- 查看所有数据库
show databases;
- 查看数据库定义
show create database 数据库名字;
- 查看当前正在使用的数据库
select databse();
- 使用数据库
use 数据库名字;
- 修改数据库
alter database character set 字符集;
3.关于数据表的基本操作
- 创建表
create table 表名(
列名1 列的类型(长度) 约束,
列名2 列的类型(长度) 约束
);
- 约束类型
主键约束 primary key;
非空约束 not null;
唯一约束 unique;
- 删除表
drop table 表名;
- 修改表
添加列
alter table 表名 add 列名 列的类型(长度) 约束;
删除列
alter table 表名 drop 列名;
修改列名
alter table 表名 change 旧列名 新列名 列的类型(长度) 约束;
修改表的字符集
alter table 表名 character set 字符集;
修改表名
rename table 旧表名 新表名;
- 查看当前数据库所有的表
show tables;
- 查看表的定义结构/创建语句
show create table 表名;
- 查看表的结构
desc 表名;
4.表中数据的基本操作
- 插入数据
insert into 表名(列名1,列名2) values(值1,值2);
insert into 表名 values(值1,值2);
批量插入
insert into 表名 values(值1,值2),values(值1,值2),values(值1,值2);
- 删除数据
delete from 表名 where 条件;
truncate table 表名;
- 更新数据
update 表名 set 列名1=值1,列名2=值2 where 条件;
- 查询数据(以下以表名=product 列名1=pid 列名2=pname 列名3=price为例)
简单查询
select * from 表名;
select 列名1,列名2 from 表名;
as查询(as 关键字可以省略)
select p.pname,p.price from pruduct as p;
select pname as 商品名称,price as 商品价格 from product;
去掉重复的值查询
select price from product;
select distince price from product;
运算查询
select price1.5 from product;
条件查询
select * from 表名 where 条件;
select * from product where price > 60;
查询price不等于8的
select * from product where price !=8;
select * from product where peice <> 8;
查询price在10到20之间的
select * from product where price>10 and price<20;
select * from product where price between 10 and 20;
模糊查询(like)
%:代表多个字符
_:代表一个字符
select * from product where pname = %酒;
select * from product where pname = _酒%;
in在某个范围之内查询
select * from product where pid in (1,2,3);
排序查询
升序
select * from product order by price asc;
降序
select * from product order by price desc;
聚合函数
select sum(price) from product;
select avg(price) from product;
select count() from product;
分组查询(以某一个值为一组,这里以id 为例)
select id,count(*) from product group by id having avg(price)>10;
关键字
having 分组查询之后可以跟having关键字。
where 出现咋分组查询之前,不可以接聚合函数。
编写顺序
select…from…where…group by…having…order by…;
执行顺序
from…where…group by…having…select…order by…;