0

我有 3 个表 obl_books、obl_authors 和链接表 books_authors。问题是:编写查询以仅选择所有作者都属于印度国籍的书籍。

我为此写的查询是

SELECT obl_books.*, books_authors.author_id
   FROM books_authors,obl_authors,obl_books
   WHERE   books_authors.author_id = obl_authors.author_id
   AND books_authors.book_id=obl_books.book_id
    GROUP BY books_authors.book_id
    HAVING  books_authors.author_id IN (SELECT obl_authors.author_id FROM obl_authors WHERE nationality='Indian')

国籍是 obl_authors 表的列,一本书可以有多个作者。

因此,如果 book_id (2) 具有 author_id (1)、author_id (2),其中 author_id (1) 和 (2) 是印度人,那么它应该返回该值,即使其中一位作者不是印度人也不应该返回。

但是我的查询甚至返回了那个 book_id。

我什至使用 ALL 关键字代替 IN 更改了我的 having 子句,但它不返回任何行。

4

5 回答 5

1

尝试:

SELECT obl_books.*, GROUP_CONCAT(books_authors.author_id)
FROM books_authors
JOIN obl_authors ON books_authors.author_id = obl_authors.author_id
JOIN obl_books ON books_authors.book_id=obl_books.book_id
GROUP BY books_authors.book_id
HAVING MIN(obl_authors.nationality)='Indian' AND 
       MAX(obl_authors.nationality)='Indian' 
于 2013-07-23T11:24:17.293 回答
1

据我了解您的问题,这就是您想要的;它只计算印度作者的数量是否与每本书的作者总数相同,并显示它们相等的地方。

SELECT b.*, GROUP_CONCAT(a.author_id) authors
FROM obl_books b 
JOIN books_authors ba ON b.book_id=ba.book_id
LEFT JOIN obl_authors a ON ba.author_id=a.author_id AND a.nationality = 'Indian'
GROUP BY b.book_id
HAVING COUNT(a.author_id)=COUNT(ba.author_id)

一个用于测试的 SQLfiddle

请注意,GROUP BYbook_id 仅是 MySQL 主义,您通常需要按obl_books.

于 2013-07-23T11:33:42.660 回答
0

I think, we can do this.. in reverse way also.. First get all the author id,who is not Indian and then except those author select all the remaining author's book (Indian Author's book).

 SELECT obl_books.*, books_authors.author_id
   FROM books_authors,obl_authors,obl_books
   WHERE   books_authors.author_id = obl_authors.author_id
   AND books_authors.book_id=obl_books.book_id AND  books_authors.author_id NOT IN (SELECT obl_authors.author_id FROM obl_authors WHERE nationality<>'Indian')
于 2013-07-23T11:21:25.217 回答
0

尝试这个

select * from obl_books where id in (select book_id from books_authors where author_id in (select id from obl_authors where nationality='Indian'))
于 2013-07-23T11:25:44.790 回答
0

试试这个查询:

SELECT obl_books.*, books_authors.author_id
   FROM books_authors,obl_authors,obl_books
   WHERE   books_authors.author_id = obl_authors.author_id
   AND books_authors.book_id=obl_books.book_id and obl_authors.nationality='Indian'
   GROUP BY books_authors.book_id
   HAVING count(books_authors.book_id) = (SELECT count(*) FROM books_authors group by books_authors.author_id)
于 2013-07-23T11:19:58.340 回答