1.数据库,表的创建、修改、查询
2.聚合函数
3.删除重复数据
4.排序
1.数据库,表的创建、修改、查询
1.1 创建:Create
user mybase --指定使用的数据库
CREATE TABLE 'mybase '.'student'{
'name' varchar(30) NOT NULL, --不能为空
'id' int(10) NOT NULL AUTO_INCREMENT, --自增
'phone' char(11) NULL, --定长
'address' varchar[200] NULL DEFAULT ‘北京', --不能没有引号
PRIMARY KEY['id'], --主键设为id
UNIQUE_INDEX 'unique_constraint_phone' ('phone'(11))
};
1.2修改: alter
alter table student add hobby --添加
alter table student drop hobby --删除
alter table student modify age int(6)--修改
1.3.查询 SELECT
1.查询所有的数据 select * from person
2.查询名字和号码 select name,phone from person
3.查询指定列名 select name as '名字',phone as '电话' from person
4.模糊搜索 '_'单一字符 '%'任意字符 select * from person where name like '朱_'
5.范围搜索 select * from person where name in('zrf','zjl','')
2.聚合函数
min() max() avg() count() sum()
having 聚合后的数据
where 原始数据
1.选择年龄最大的 select max(age) from person
2.选择年龄最小的 select min(age) from person
3.选择个数 select count(*) from person
4.求和 select sum(age) from person
5.每个班的平均 select avg(age) from person group by cls
6.每个班的最大 select max(age) from person group by cls
7.除了聚合函数外,都要写在group by 后
select id,cls,max(age) from person group by cls
8.查询每个班有多少人
select cls,count(*)from person group by cls
9.查询出班级人数超过2人的班级
select cls,count(*)from person group by cls having count(*)>2
3.删除重复数据
3.1查询重复数据 :
select name ,age from tt group by name having count(*)>=2
3.2删除重复数据:
删除重复数据 ,保留最小id,如果数据不重复,保留该数据
1.查询出要保留的数据 select min(id) from tt group by name ,age
2.删除重复的 delete from tt where id not in(select min(id) from tt group by name ,age)不可用
mysql 不允许同时delete select
a:创建了一个查询结果,且定义并放入到了t中。 (select min(id) from tt group by name,age) t
表头叫 min(id) 把它改成 id min(id) as id
所以现在的语句是 (select min(id)as id from tt group by name ,age) t
b:从t中选一个id字段 select from tt where id not in (select min(id) as id from tt group by name,age) t 此句不可用做
C:添加一层选择 select from tt where id not in (select id from (select min(id) as id from tt group by name,age) t)
4.排序asc:升序 12345 desc:降序 54321
4.1 按年龄升序排列 select * from student order by age asc
4.2 按年龄降序,电话号码升序select * from student order by age desc,phone asc
4.3按年龄 升序排列 select name ,age as 年龄 from student order by 年龄