我使用发布数据库,并保存书籍记录。书籍可以有多位作者。我们维护着一张表,其中记录了书籍的作者身份。我需要一个SQL查询来选择一个作者,然后选择在他们的每本书上使用它们的其他作者。
Authorship表格如下所示:
+---------+--------+
| Author | BookID |
+---------+--------+
| 1 | 1 |
| 2 | 1 |
| 1 | 2 |
| 2 | 2 |
| 3 | 2 |
| 4 | 2 |
| 5 | 3 |
| 5 | 4 |
+---------+--------+
因此,如果我选择作者1,我希望看到他们合作的作者。结果将使我回复作者2,3和4。
这里的想法是,我可以为作者生成一份报告,说明他们在出版事业中与谁合作。
答案 0 :(得分:2)
select a1.Author
from Authorship a
join Authorship a1 on a.BookID=a1.BookID
where a.Author=1
If you want to exclude the current author:
select a1.Author
from Authorship a
join Authorship a1 on a.BookID=a1.BookID
where a.Author=1 and a1.Author!=1
答案 1 :(得分:2)
试试这个:
SELECT author
FROM AuthorsBooks
WHERE bookid IN(SELECT bookid
FROM AuthorsBooks
WHERE author = 1);
这会给你:
| AUTHOR |
----------
| 1 |
| 2 |
| 3 |
| 4 |
或:使用JOIN
:
SELECT DISTINCT b1.author
FROM AuthorsBooks AS b1
INNER JOIN AuthorsBooks AS b2 ON b1.bookid = b2.bookid
WHERE b2.author = 1;
答案 2 :(得分:1)
这是你能做的。
SELECT DISTINCT Author
FROM Authorship
WHERE BookID IN(
SELECT BookID
FROM Authorship
WHERE Author = 1
)
AND Author <> 1