我有一个数据库,用于保存书籍及其作者。在我的模型中,一位作者可以拥有多本书,而一本书可以由多位作者撰写。示例:
AUTHOR_ID|BOOK_ID
1|100
1|200
1|300
2|300
3|300
4|400
我正在尝试让作者只写过一本书,并且该书必须仅由该作者单独撰写。在上面的示例中,只有 AUTHOR_ID = 4 才是有效的作者。
我需要编写一个 select 来获取满足上述要求的作者 id,我如何编写快速高效的 select 来执行此操作?
最佳答案
select *
from BookAuthors t1
where not exists (select * from BookAuthors t2
where t2.BOOK_ID = t1.BOOK_ID
and t2.Author_ID <> t1.Author_ID)
and not exists (select * from BookAuthors t3
where t3.Author_ID = t1.Author_ID
and t3.BOOK_ID <> t1.BOOK_ID)
第一个 NOT EXISTS
是为了确保同一 bookid 没有第二位作者。
第二个 NOT EXISTS
是为了确保相同的 Author_ID 没有写过另一本书。
组合版本:
select *
from BookAuthors t1
where not exists (select * from BookAuthors t2
where (t2.BOOK_ID = t1.BOOK_ID
and t2.Author_ID <> t1.Author_ID)
or (t2.Author_ID = t1.Author_ID
and t2.BOOK_ID <> t1.BOOK_ID))
关于sql - 如何从多对多表中选择一对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35844164/