sql 多表连接查询
网络整理 - 08-24
新建两张表:
表1:student 截图如下:
表B: course 截图如下:
表C: student_course 截图如下:
一个学生可以选择多门课程,一门课程可以被多个学生选择,因此学生表student和课程表course之间是多对多的关系。
当两表为多对多关系的时候,我们需要建立一个中间表student_course,中间表至少要有两表的主键,当然还可以有别的内容。
SQL语句:select s.Name,C.Cname from student_course as sc left join student as s on s.Sno=sc.Sno left join course as c on c.Cno=sc.Cno
执行结果:
此条SQL执行的结果是学生选课的情况。
以下是特色补充:
select * from (SELECT id,jihao, ht.hetongid, hetonghao, banshichu, zulindanwei, jiansheluduan, shebeijinchangriqi,hetongfangshi,
jine,yusuangongchengliang,(ht.jine/30)*(datediff(day,ht.shebeijinchangriqi,getdate())) as yusuanjine,yihuikuanjine,
((ht.jine/30)*(datediff(day,ht.shebeijinchangriqi,getdate()))-yihuikuanjine) as qiankuanjine,ht.shebeituichangriqi
FROM db_hetongguanli_y_g as ht left join select sum (gongchengliang) as yusuangongchengliang ,hetongid
from db_meirigongchengliang group by hetongid) as d on ht.hetongid=d.hetongid left
join(select sum(shijihuikuanjine) as yihuikuanjine,hetongid from db_huikuan group by hetongid) as a on ht.hetongid=a.hetongid ) as b
where b.hetongfangshi='月租' and b.hetongid=(select hetongid from db_shebeixinxi where jihao='" + this.DropDownList1.SelectedValue + "')";
==================================================================================================
select * from (select ht.id,ht.qiandingren,ht.hetongid,ht.banshichu,ht.jihao,ht.hetonghao,ht.zulindanwei,
ht.jiansheluduan,ht.qingqianriqi,ht.lumianshigongcailiao,ht.hetongfangshi,ht.jine,ht.hetongqiandingriqi,
ht.hetongjiesuanjine,ht.hetongjiesuanriqi,ht.shebeijinchangriqi,ht.shebeituichangriqi,ht.jiesuangongchengliang,
d.yifukuanjine, (ht.hetongjiesuanjine-d.yifukuanjine) as qiankuanjine,ht.kaipiaojine,ht.ranyoufei,ht.yunfei,
ht.qitafeiyong,ht.feiliaofei from db_hetongguanli_y_g as ht left join (select hetongid,sum(shijihuikuanjine) as yifukuanjine
from db_huikuan group by hetongid) as d on ht.hetongid=d.hetongid) as a
where a.hetongid=(select hetongid from db_shebeixinxi where jihao='5666')
go