sql:group by和having子句问题

时间:2013-07-23 11:14:56

标签: mysql

我有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子句,但它没有返回任何行..

请帮助:(

5 个答案:

答案 0 :(得分: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' 

答案 1 :(得分: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)

An SQLfiddle to test with

请注意,book_id上的GROUP BY只是一种MySQL主义,您通常需要按obl_books中的所有选定字段进行分组。

答案 2 :(得分: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)

答案 3 :(得分: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  books_authors.author_id NOT IN (SELECT obl_authors.author_id FROM obl_authors WHERE nationality<>'Indian')

答案 4 :(得分: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'))
相关问题