如何编写DQL查询筛选与指定教师教育阶段匹配的书籍
实现方案(基于DQL/SQL)
现有数据库表
Book表
| id | book_title |
|---|---|
| 1 | a |
| 2 | b |
| 3 | c |
| 4 | d |
Teacher表
| id | teacher_name |
|---|---|
| 1 | a |
| 2 | b |
| 3 | c |
| 4 | d |
Education_stage表
| id | education_stage_name |
|---|---|
| 1 | a |
| 2 | b |
| 3 | c |
| 4 | d |
书籍与教育阶段关联表(book_education_stage)
| book_id | education_stage_id |
|---|---|
| 1 | 1 |
| 1 | 2 |
| 2 | 3 |
| 3 | 4 |
书籍与教师关联表(book_teacher)
| book_id | teacher_id |
|---|---|
| 1 | 1 |
| 1 | 4 |
| 2 | 3 |
| 3 | 4 |
查询需求
筛选出与id=1的教师拥有相同教育阶段的书籍,预期结果:
| book_id | title |
|---|---|
| 1 | a |
实现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 );
语句解释
- 子查询部分:通过
book_teacher表定位id=1的教师关联的书籍,再关联book_education_stage表得到这些书籍对应的教育阶段ID集合(此处为1和2)。 - 主查询:关联
Book表和book_education_stage表,筛选出关联的教育阶段ID属于上述集合的书籍,用DISTINCT避免同一书籍因关联多个符合条件的教育阶段而重复输出。
执行该语句后会得到预期结果——仅book_id=1的书籍,因为只有它关联了id=1的教师对应的教育阶段,其他书籍的教育阶段均不在此范围内。
内容的提问来源于stack exchange,提问作者dosad
相关产品推荐
相关产品推荐

