程序员一年半了,其实到现在我还是不怎么明白那些连接的问题。 特别是当业务复杂的时候,我很担心连接出来的数据有很多冗余,所有很多时候,用子查询,in 和 not in 和外连接似乎更有把握些。 select * from tb_class
select * from tb_student
select * from tb_class c where c.classid in (select distinct(t.stu_classid) from tb_student t) 要达到这个效果。用连接可以达到吗?
select c.* from tb_class , tb_student where ??????????????????
---------------------------------------------------------------------------------------------
有没有什么书,可以让我比较清楚学习各种连接。 至少不会犯错误。
---------------------------------------------------------------------------------------------
假设班级表有一个属性:班级得分。select s.* , c.score from tb_student s , tb_class c where s.stu_classid = c.classid and s.age>16 我想求:所有在所有大于16岁的学生,所在的班级的 班级得分的总和。 以下语句肯定重复计算了。 有没有什么办法,
在不改变【】外的固定语句情况下,查询到我想要的结果。
select 【 sum(c.score) 】 from tb_student s , tb_class c where s.stu_classid = c.classid and s.age>16
--- 不对
select * from tb_student
select * from tb_class c where c.classid in (select distinct(t.stu_classid) from tb_student t) 要达到这个效果。用连接可以达到吗?
select c.* from tb_class , tb_student where ??????????????????
---------------------------------------------------------------------------------------------
有没有什么书,可以让我比较清楚学习各种连接。 至少不会犯错误。
---------------------------------------------------------------------------------------------
假设班级表有一个属性:班级得分。select s.* , c.score from tb_student s , tb_class c where s.stu_classid = c.classid and s.age>16 我想求:所有在所有大于16岁的学生,所在的班级的 班级得分的总和。 以下语句肯定重复计算了。 有没有什么办法,
在不改变【】外的固定语句情况下,查询到我想要的结果。
select 【 sum(c.score) 】 from tb_student s , tb_class c where s.stu_classid = c.classid and s.age>16
--- 不对
select sum(c.score) from tb_student s , tb_class c where s.stu_classid = c.classid and s.age>16
group by c.classid
内连接(inner join),相当于取交集,即2个表的共有部分.
外连接(outer join)分为
左连接(left join),左表+公共部分.
右连接(right join),右表+公共部分.
from (
select sum(c.score) as SCORE
from tb_student s , tb_class c
where s.stu_classid = c.classid
group by c.classid
having min(s.age) > 16
) a
2. 如果是:至少有一个大于 16 岁的学生的班级的得分总和:select sum(SCORE)
from (
select sum(c.score) as SCORE
from tb_student s , tb_class c
where s.stu_classid = c.classid
group by c.classid
having max(s.age) > 16
) a
表:tb_class classid:主键
表:tb_student stuid:主键 stu_classid:外键(classid)
假如:班级表有,20个班级。
我想查 tb_class 的情况
select c.* from tb_class c where c.classid in (select distinct(t.stu_classid) from tb_student t) -----------------------------------------------
但是如果用:连接。 查出来的结果>20 。
from tb_class c, (select distinct classid from tb_student s where age>16) s
where s.stu_classid = c.classid
;