python——數(shù)據(jù)庫高級查詢

分組,姓名:每個人的總分

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;
自關(guān)聯(lián)
create table areas(
aid int primary key auto_increment not null,
atitle varchar(20),
pid int,
foreign key(id) references areas(id)
);

從sql文件導入數(shù)據(jù)庫

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(一種數(shù)據(jù)庫引擎)或者bdb類型才可以對此表使用事務
使用事務的情況:
當數(shù)據(jù)被更改時,包括insert,update,delete
事務的命令:
begin:開始
commit:提交
rollback:回滾
只有commit之后才能更新成功,否則,只是暫時存在一個臨時的表中

索引

索引太多會導致物理消耗很大
查看索引:

show index from table_name

創(chuàng)建索引

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

刪除索引

drop index [indexname] on mytable

索引會大大提高查詢的速度,同時也會降低更新表的速度,建立索引會占用磁盤的索引文件

set profiling=1;
自關(guān)聯(lián)

物理上是一張表,邏輯上是多張表。
自關(guān)聯(lián)查詢時必須得起別名。

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);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容