MySQL(1)

常用数据库命令
1.查询所有数据库
show databases
2.创建数据库
create databases [if not exists] db106
3.创建数据库指定字符集
create database db604
character set utf8
collate utf8_general_ci;
4.显示数据库创建语句
show create database db604
5.删除数据库
drop database db604

表命令 student 表
切换使用数据库
use db604
1.查看所有表
show tables
2.创建表
create table [if not exists] student (
name varchar(10),
age int ,
sex char(2),
)
区别char和varchar
char()固定长度
varchar()可变长度

3.查看表结构
show create table student ——>查看创建表语句
desc student ——–>查看表结构
4.删除表
drop table student
5.修改表
alter table 表名 add / drop / modify / change / column 列名、类型等信息

添加字段(添加列)
alter table student add column math int;
删除列
alter table student drop column age;
修改字段类型
alter table student modify column sex varchar(10);
修改字段名称
change column 原来的名 新的名 类型
alter table student change column sex gender varchar(10);
修改表名
alter table student rename to user

数据库操作语句(增删改数据)
1.插入数据
insert into student(id , name , sex) values(1 , ‘张三’ , ‘男’)
2.修改数据
update student set name =’李四’ where id=1;
3.删除数据
delete from student where id =1;

查询数据
1.查询所有数据
select * from student
2.查询指定列数据
select id ,name from student
3.查询时指定常量列(别名)
select id , name as 姓名 from student
4.查询时去除重复数据
select distinct from student
5.查询时合并
select id, name ,age,java+math as 总成绩 from student
6.按条件查询
select *from student where id = 2;
a. 逻辑条件查询,涉及多个条件 and &&(与) or (或)
select *from student where id= 2 and name = ‘李四’;
select * from student where name =’李四’ or age =22;
b.比较条件查询 > >= < <= = <>(不等于) between and(谁和谁之间)
select * from student where id<>2;
c.判断是否为空
select * from student where age is null
select *from student where age is not null
d.模糊查询
select * from user where name like ‘zhao%’;
select * from user where name like ‘%s%’;
select * from user where name like ‘zhaos_’;

7. 通过聚合函数查询
a.计算表中有多少条数据(行)count
eg: select count(*) from user;
b. 如果某些行对应的列没有数据,不计算到总数里
eg: select count(age) from user;

c.求平均值 avg
eg:select avg(age) from user
d.求最大值和最小值
eg: select min(age) from user;
eg: select max(age) from user;
f. 求和 sum
select sum(age) from user;
sum() 该列所有数据总和
+ : 该行数据相加的和

8.排序 order by
eg: select * from user order by age;
eg: select * from user where age is not null order by age;

desc表示降序,asc表示升序,默认升序
eg: select * from user where age is not null order by age desc;

可以指定多个排序的字段,例如先按照age排序,相同的age值再使用id排序
eg:select * from user where age is not null order by age,id;
eg:select * from user where age is not null order by age desc,id desc;

9 分组查询 group by
eg: select gender, count(*) from user group by gender;
eg:select gender,count(*) from stu group by gender order by gender desc;

having 对分组后的数据进行筛查
where 放在分组前使用
mysql> select gender,count() from user where age is not null group by gender having count()>1 order by gender desc;

10 分页查询 limit
Limit 从哪个位置开始查(索引从0开始计数), 查询多少条数据
mysql> select * from user limit 3,3;

表示从0位置开始查询3条数据
mysql> select * from user limit 3;

你可能感兴趣的:(MySQL,MySQL基本操作语句)