分組,姓名:每個人的總分
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);