帮我看看这个sql语句

2024-12-29 20:41:22
推荐回答(4个)
回答1:

takes这个表如果是选课信息表的话,我个人认为关联的条件不会这么多,应该通过course_id一个字段限制就够了。当然不了解你的这两张表结构,答案仅供参考。你的这个IN查询基础概念很模糊,应该好好了解下IN、EXINSTS的用法才是。
IN:
select count(ID)
from takes
where course_id in (select course_id from teaches where teaches.ID='10101')

EXISTS:
select count(ID)
from takes a
where exists(select 1 from teaches where ID='10101' and course_id=a.course_id)

INNER JOIN:
select count(a.ID)
from takes a inner join teaches b
on a.course_id=b.course_id
where b.ID='10101'

回答2:

改用exists:
select count(distinct ID)
from takeswhere a
where exists (select 1
from teaches b
where a.course_id = b.course_id
and a.sec_id = b.sec_id
and a.semester = b.semester
and a.year = b.year
and b.ID = '10101')
写有子查询作为条件时,最好用exists,一般情况下这个性能会比IN好一些,但不绝对。

回答3:

select select count(distinct ID) from takes innerjoin teaches
on takes.course_id=teaches.course_id and takes.sec_id=teaches.sec_id and takes.semester=teaches.semester and takes.year= teaches.year
where teaches.ID='10101'

回答4:

找出选修了ID位10101的教师所讲授的课程的学生人数

这种情况, 可以简单关联一下就可以了.

SELECT
count(distinct ID)
FROM
takes JOIN teaches
ON (
takes.course_id = teaches.course_id
AND takes.sec_id = teaches.sec_id
AND takes.semester = teaches.semester
AND takes.year = teaches.year
AND teaches.ID='10101'

)