繁体   English   中英

如何从多对多表中选择一对一关系

[英]How to select one to one relations from many to many table

我有一个数据库,用于存放书籍及其作者。 在我的模型中,一位作者可以有很多书,而一本书可以由很多作者写。 例:

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))

这是一个单独的答案,因为第一个错误。

如果您的数据库支持窗口函数,则一种方法是:

select Author_ID
from (select ba.*, count(*) over (partition by Author_ID) as numBooks,
             count(*) over (partition by Book_ID) as numAuthors
      from BookAuthors ba
     ) ba
where numBooks = 1 and numAuthors = 1;

通过将条件移至where子句或join s,也可以通过多种方式进行:

select ba.*
from BookAuthors ba
where Author_ID in (select Author_Id from BookAuthors group by Author_Id having count(*) = 1) and
      Book_ID in (select Author_Id from BookAuthors group by Book_ID having count(*) = 1);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM