分組蔫仙,姓名:每個(gè)人的總分
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文件導(dǎo)入數(shù)據(jù)庫(kù)
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 = '山東')
事務(wù)
事務(wù)的四大特性:
1、原子性
2剔猿、一致性
3癞松、隔離性
4爽撒、持久性
表的類型必須是innodb(一種數(shù)據(jù)庫(kù)引擎)或者bdb類型才可以對(duì)此表使用事務(wù)
使用事務(wù)的情況:
當(dāng)數(shù)據(jù)被更改時(shí),包括insert响蓉,update硕勿,delete
事務(wù)的命令:
begin:開始
commit:提交
rollback:回滾
只有commit之后才能更新成功,否則枫甲,只是暫時(shí)存在一個(gè)臨時(shí)的表中
索引
索引太多會(huì)導(dǎo)致物理消耗很大
查看索引:
show index from table_name
創(chuàng)建索引
create index indexname on mytable(username(length));
刪除索引
drop index [indexname] on mytable
索引會(huì)大大提高查詢的速度源武,同時(shí)也會(huì)降低更新表的速度,建立索引會(huì)占用磁盤的索引文件
set profiling=1;
自關(guān)聯(lián)
物理上是一張表想幻,邏輯上是多張表粱栖。
自關(guān)聯(lián)查詢時(shí)必須得起別名。
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);