简体   繁体   中英

MYSQL: How can i select a specific row in this situation?

SELECT name 
FROM books 
WHERE book_id IN (
    SELECT book_id 
    FROM details 
    WHERE lang IN ('English') 
    GROUP BY book_id 
    HAVING COUNT(book_id)=1
); 

My details table is like:


1            English
1            Spanish
1            French
2            English
3            Spanish
3            French
4            German
4            English

How can I select which books are written only in English like book_id = 2?

When I write my code, I receive which book_id's contains 'English' lang, but I want to get books which have exactly 1 language, and this language is 'English'.

You can use not exists :

select b.*
from books b
where not exists (select 1
                  from details d
                  where d.book_id = b.book_id and
                        d.lang <> 'English'
                 );

That is: There is no language other than English.

Note: If a book does not have details, then it will also be returned. If you want to avoid that, you can use aggregation:

select b.*
from books b join
     details d
     using (book_id)
group by b.book_id
having min(lang) = 'English' and max(lang) = 'English';

Assuming that lang is never null use the HAVING clause to set the condition:

SELECT name 
FROM books
WHERE book_id IN (
  SELECT book_id
  FROM details
  GROUP BY book_id
  HAVING SUM(lang <> 'English') = 0
) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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