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

复合主键与外键多对多关联场景下如何查询指定作者的书籍

正确SQL语句及说明

你原有查询的问题是没有为三张表添加关联匹配条件,仅筛选了authors_Books.authorId=1,会触发多表笛卡尔积,返回大量不符合预期的重复数据。

符合要求(不使用JOIN语法)的正确SQL如下:

select 
  books.bookTitle, 
  books.price, 
  books.publisher, 
  authors.firstName, 
  authors.lastName 
from 
  books, 
  authors, 
  authors_Books 
where 
  -- 关联作者表和中间关联表
  authors.authorId = authors_Books.authorId
  -- 关联书籍表和中间关联表
  and books.bookId = authors_Books.bookId
  -- 筛选作者ID为1(即Mark Dunn)的记录
  and authors_Books.authorId=1 ;

如果不想硬编码作者ID,也可以通过姓名做筛选:

select 
  books.bookTitle, 
  books.price, 
  books.publisher, 
  authors.firstName, 
  authors.lastName 
from 
  books, 
  authors, 
  authors_Books 
where 
  authors.authorId = authors_Books.authorId
  and books.bookId = authors_Books.bookId
  and authors.firstName = 'Mark'
  and authors.lastName = 'Dunn';

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 21:45:03