1.注释
单行注释:-- 注释内容(两个横杠之后有空格,不然报错)
或者 #注释内容
多行注释: /*注释 */
2.DDL 操作数据库和表
score double(total length,小数点后保留的位数)
图形化客户端工具:navicat
create database if no exists db1;
drop database if exists db2;
select database();#查看当前使用的数据库
use db1;
show tables;#查询当前数据库下所有表名称
desc tablename;#查询表结构
create table tablename(
id int,
name varchar(20),
age varchar(20)
);
drop table if exists tablename;
#修改表
alter table tablename rename to newTablename;
alter table tablename add columnname datatype;
alter table tablename modify columnname newdatatype;
alter table tablename change newcolumnname newdatatype;
alter table tablename drop columnname;
3.DML操作数据
inset into tablename(columnname1,columnname2) values(value1,value2);#指定列添加数据
inset into tablename values(valueq,value2);
4.DQL 查询
4.1基础查询
--去除重复记录
select distinct address from stu;
4.2条件查询
--查询年龄大于等于20 并且 年龄小于三十
select *from stu where age>=20 && age<30;
select *from stu where age>=20 and age<30;
select *from stu where age between 20 and 30;
--不等于18
select *from stu where age !=18;
select *from stu where age <>18;
--或者 or ||
select *from stu where age in (18,20,22);
--is null
--is not null
--like模糊查询 _单个字符 %通配符
where name like "张%"
where name like "_张%"
where name like "%张%"
4.3排序查询
--别名
select name,math as shuxue from stu;
--年龄升序asc 默认 desc 降序
order by age ASC
--数学降序,一样,英语升序
select *from stu order by math desc,english as;
4.4分组查询
4.4.1聚合函数(null值不参与所有聚合函数的运算)
select 聚合函数(列名)from 表;
--group by
--count 统计数量 不为空即可
select count(id) from stu;
select count(*) from stu;
--max
--min
--sum
--avg
4.4.2分组查询
select 字段列表 from 表名 [where 分组前条件限定] group by 分组字段名 [having 分组后条件过滤]
--查询男同学和女同学各自的数学平均分
select avg(math) from stu group by sex;
--显示分组的性别
select sex,avg(math) from stu group by sex;
--注意,分组之后,查询的字段为聚合函数和分组字段,查询其他字段无任何意义(即这时候前面加个name 但是此时是全部的平均分,没办法为整体命名一个人的名字)
--以及各自的平均分
select sex,avg(math),count(*) from stu group by sex;
--分数低于70分不参与分组
select sex,avg(math),count(*) from stu where math>70 group by sex;
--分组之后人数大于2
select sex,avg(math),count(*) from stu where math>70 group by sex having count(*)>2;
where:在分组之前进行限定,不满足where条件则不参与分组,而having是分组之后对结果进行过滤。(where不能对觉和函数进行判断)
执行顺序:where>聚合函数>having
4.5分页查询
select 字段列表 From 表名 limit 起始索引 ,查询条目
起始索引从0开始
起始索引=(当前页数-1)*每页显示的条数
--从0开始查询,查询3条数据
select * from stu limit 0,3;
--oracle rownumber
--sql server分页查询用top
--mysql limit