-2

I work with a publishing database and we keep records of books. Books can have multiple authors. We maintain a table which holds records of the authorship of books. I need a SQL Query to select an author and then also select the other authors who worked with them on each of their books.

The Authorship table looks something like this:

+---------+--------+
| Author  | BookID |
+---------+--------+
|    1    |    1   |
|    2    |    1   |
|    1    |    2   |
|    2    |    2   |
|    3    |    2   |
|    4    |    2   |
|    5    |    3   |
|    5    |    4   |
+---------+--------+

So if I selected Author 1 I want to see the authors they worked with. The result would return me authors 2,3, and 4.

The idea here is that I can generate a report for an Author that shows who they have collaborated with in their publishing career.

4

3 回答 3

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
于 2013-03-05T08:05:40.190 回答
2

Try this:

SELECT author
FROM AuthorsBooks 
WHERE bookid IN(SELECT bookid
                FROM AuthorsBooks
                WHERE author = 1);

SQL Fiddle Demo

This will give you:

| AUTHOR |
----------
|      1 |
|      2 |
|      3 |
|      4 |

Or: using JOIN:

SELECT DISTINCT b1.author
FROM AuthorsBooks AS b1
INNER JOIN AuthorsBooks AS b2  ON b1.bookid = b2.bookid
WHERE b2.author = 1;

SQL Fiddle Demo

于 2013-03-05T08:06:13.023 回答
1

Here is what you can do.

SELECT DISTINCT Author  
FROM Authorship 
WHERE BookID IN(  
            SELECT BookID   
            FROM Authorship  
            WHERE Author = 1  
           ) 
AND Author <> 1

SQL FIDDLE DEMO

于 2013-03-05T08:24:03.817 回答