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

如何编写DQL查询筛选与指定教师教育阶段匹配的书籍

实现方案(基于DQL/SQL)

现有数据库表

Book表

idbook_title
1a
2b
3c
4d

Teacher表

idteacher_name
1a
2b
3c
4d

Education_stage表

ideducation_stage_name
1a
2b
3c
4d

书籍与教育阶段关联表(book_education_stage)

book_ideducation_stage_id
11
12
23
34

书籍与教师关联表(book_teacher)

book_idteacher_id
11
14
23
34

查询需求

筛选出与id=1的教师拥有相同教育阶段的书籍,预期结果:

book_idtitle
1a

实现SQL语句

SELECT DISTINCT b.id AS book_id, b.book_title AS title
FROM Book b
JOIN book_education_stage bes ON b.id = bes.book_id
WHERE bes.education_stage_id IN (
    -- 获取id=1的教师关联书籍对应的所有教育阶段ID
    SELECT bes_inner.education_stage_id
    FROM book_teacher bt
    JOIN book_education_stage bes_inner ON bt.book_id = bes_inner.book_id
    WHERE bt.teacher_id = 1
);

语句解释

  1. 子查询部分:通过book_teacher表定位id=1的教师关联的书籍,再关联book_education_stage表得到这些书籍对应的教育阶段ID集合(此处为1和2)。
  2. 主查询:关联Book表和book_education_stage表,筛选出关联的教育阶段ID属于上述集合的书籍,用DISTINCT避免同一书籍因关联多个符合条件的教育阶段而重复输出。

执行该语句后会得到预期结果——仅book_id=1的书籍,因为只有它关联了id=1的教师对应的教育阶段,其他书籍的教育阶段均不在此范围内。

内容的提问来源于stack exchange,提问作者dosad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 18:24:26