这是我参与 [第四届青训营] 笔记创作活动的第2天
在完成青训营后面的大项目时,我写完了xml文件后,不知道接口怎么用,怎么和数据库的内容进行联系,于是,我又开始继续学习暑期未学完的 Javaweb 。 首先记录一下里面的MYSQL语句,虽然在Android里面用的是SQLite
添加数据insert:
1.给指定列添加数据
添加单条数据
insert into 表名(列名) values(值);
例:insert into stu(id,name) values(1,'张三');
批量添加数据
insert into 表名(列名) values(值),(值),(值),(值);
例:insert into stu(id,name) values(1,'张三'),(2,'李四'),(3,'王二'),(4,'麻子');
修改数据update:
update 表名 set 列名1=值1,列名2=值2,......[where 条件];
例:update stu set sex='女' where name='张三';
删除数据delete:
delete from 表名 [where 条件];
例:delete from stu where name='张三';
DQL
基础查询select:
1.去除重复记录distinct
select distinct address from stu;
2.替换原始的列名as(便于用户理解)
select name as 姓名,math as 数学成绩,english as 英语成绩 from stu;
条件查询where:
1.where age > 20;大于
2.where age >= 20;大于等于
3.where age > 20 and age<30 ;大于且小于,并且 或者 可以这样写:=> where age between 20 and 30;
4.!= 不等于 或者 可以这样写:<>
5.where age=18 or age=20 or age=22; => where age in (18,20,22);
6.查询成绩不为null的信息:where english is null ; <=> where english is not null ;
7.模糊查询:
(1)_:代表单个任意字符
(2)%:代表任意个数字符
例:
where name like '马%';
where name like '_马%';
排序查询order by:
1.升序 asc , 降序 desc
单一的排序
例: select * from stu order by age asc;
先按照某一列降序排序,如果一样则按照另外一列升序排序
例: select * from stu order by math desc ,english asc;
分组查询:
(聚合函数)group by:
*null值不参与所有的聚合函数运算
1.count(列名):
select count(id) from stu;
2.max(列名):~
3.min(列名):~
4.sum(列名):~
5.avg(列名):~
(分组函数)HAVING:
where与having的区别:
执行时机不一样:where是分组之前进行限定,不满足where条件,则不参与分组,而having则是分组后对结果进行过滤。
可判断的条件不一样:where 不能对聚集函数进行判断,having可以。
select sex,avg(math),count(✳) from stu where math > 70 group by sex having count(✳) > 2; 分组之后人数大于2的
分页查询limit:
select 字段列表 from 表名 limit 起始索引 , 查询条目数 //(起始索引为0)
1.从0开始查询,查询3条数据
2.每页显示3条数据,查询第1页数据
select * from stu limit 0,3;
--起始索引动态变化
起始索引公式:
起始索引=(当前页码-1)* 每页显示的条数
外键约束foreign key:
添加外键:alter table emp add constraint(约束) fk_emp_dept foreign key(dep_id) references dept(id);
删除外键:alter table emp drop foreign key fk_emp_dept;
一对多:
实现方式:在多的一方建立外键关联一的一方主键
多对多:
实现方式:建立第三张中间表,中间表至少包含两个外键,分别关联两方主键
一对一:
显式内连接:
select *
from emp
join dept emp on dep_id=dept.did;
隐式内连接:
select *
from emp
where 条件