You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

《Database System Concept》习题SQL查询:我的写法是否符合要求?

Is the Multi-Column Subquery Required Here?

No, you don’t strictly have to use the exact subquery structure from the参考答案, but your current approach won’t give you the correct result. Here’s why:

The Problem With Your Query

Your query uses course_id IN (SELECT course_id FROM teaches WHERE ID=10101), which would count all students who took any section of courses that teacher 10101 has ever taught—including sections taught by other teachers in different semesters or years. That’s not what the question asks for; we need students who took sections specifically taught by teacher 10101.

Why the参考答案 Works

The参考答案 uses the combination of (course_id, sec_id, semester, year) because these four columns together uniquely identify a single course section in both the teaches and takes tables. This ensures you’re only matching students who enrolled in sections that teacher 10101 actually led.

Equivalent Alternatives (Not Just the Exact Form)

You can achieve the same correct result with other SQL structures, as long as you match all four section-identifying columns:

Using a JOIN (Often More Readable)

SELECT COUNT(DISTINCT t.ID)
FROM takes t
JOIN teaches te 
  ON t.course_id = te.course_id 
  AND t.sec_id = te.sec_id 
  AND t.semester = te.semester 
  AND t.year = te.year
WHERE te.ID = 10101;

Using an EXISTS Subquery

SELECT COUNT(DISTINCT ID)
FROM takes t
WHERE EXISTS (
    SELECT 1 
    FROM teaches te
    WHERE te.ID = 10101
      AND te.course_id = t.course_id
      AND te.sec_id = t.sec_id
      AND te.semester = t.semester
      AND te.year = t.year
);

Key Takeaway

The critical thing is that you can’t rely solely on course_id to link the two tables—you need to match all columns that define a unique course section. The参考答案’s form is one valid way to do this, but there are other equally correct approaches.

内容的提问来源于stack exchange,提问作者장수환

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:46:17