python——数据库高级查询

分组,姓名:每个人的总分

select name, sum(score)
form students
inner join scores on students.id = scores.stuid
where gender=1
group by students.id

查询科目名称和平均分

select subjects.stitle, avg(scores.score)
from scores
inner join subjects on score.subid = subjects.id
group by subjects.stitle 

查询未删除科目的名称,最高分,平均分

select subjects.stitle, avg(scores.score), max(scores.score)
from scores
inner join subjects on scores.subid = subjects.id
where subjects.isdelete = 0
group by subjects.stitle;
自关联
create table areas(
aid int primary key auto_increment not null,
atitle varchar(20),
pid int,
foreign key(id) references areas(id)
);

从sql文件导入数据库

source areas.sql;
视图
create view v_stu_sub_sco as
select * from scores
inner join students on scores.stuid = students.id
inner join subjects on scores.subid = subjects.id

show tables可以看见视图

select * from v_1

也可以修改视图

alter view v_stu_sub_sco as
select * from scores
inner join students on scores.stuid = students.id
inner join subjects on scores.subid = subjects.id
where stu.isdelete = 0 and sub.isdelete = 0;
select * from areas where
pid=(select id from areas where title = '山东')
事务

事务的四大特性:
1、原子性
2、一致性
3、隔离性
4、持久性
表的类型必须是innodb(一种数据库引擎)或者bdb类型才可以对此表使用事务
使用事务的情况:
当数据被更改时,包括insert,update,delete
事务的命令:
begin:开始
commit:提交
rollback:回滚
只有commit之后才能更新成功,否则,只是暂时存在一个临时的表中

索引

索引太多会导致物理消耗很大
查看索引:

show index from table_name

创建索引

create index indexname on mytable(username(length));

删除索引

drop index [indexname] on mytable

索引会大大提高查询的速度,同时也会降低更新表的速度,建立索引会占用磁盘的索引文件

set profiling=1;
自关联

物理上是一张表,逻辑上是多张表。
自关联查询时必须得起别名。

create table rooms(
id int primary key not null,
title varchar(10));

create table stu(
id int primary key auto_increment not null,
name varchar(10),
roomid int);

alter table stu add constraint stu_room foreign key(roomid) reference rooms(id);

你可能感兴趣的:(python——数据库高级查询)