简体   繁体   中英

How to implement a subquery to select rows that match two out of three topics?

How can I find any books which cover exactly two of three different SQL systems without the set operator. I am using three topic ids 'SSRV', 'ORA', 'MySQL' and need to output 2 out of any three. For example, the book could have a topic of SSRV and a topic of ORA, but not MySQL. Any two combination of these topics is sufficient to pass our filter.

I want to display the book_id and title of the book(s) that meet this test.

  SELECT book_id
       , title
    FROM a_bkinfo.books B
   WHERE book_id IN (
       SELECT book_id
         FROM a_bkinfo.book_topics BT
    WHERE topic_id = 'SSRV' )
  AND book_id IN (
       SELECT book_id
         FROM a_bkinfo.book_topics BT
    WHERE topic_id = 'ORA' )
  AND book_id IN (
       SELECT book_id
         FROM a_bkinfo.book_topics BT
    WHERE topic_id = 'MySQL' )
  AND book_id IN (
        SELECT COUNT(*) 
                   FROM (  
                       SELECT book_id
                           ,  count(topic_id) AS topics
                         FROM a_bkinfo.book_topics BT 
                        GROUP BY book_id
                        HAVING count(topic_id) = 2
                        ) t 
              ;  

UPDATED VERSION:

   SELECT book_id
 , title
 FROM a_bkinfo.books B
 WHERE book_id IN (
       SELECT book_id
         FROM a_bkinfo.book_topics BT
    WHERE topic_id ='SSRV'
        OR topic_id ='ORA' )
AND book_id IN (
        SELECT book_id
          FROM a_bkinfo.book_topics BT
    WHERE topic_id ='SSRV' 
        OR topic_id ='MySQL')
AND book_id IN (
        SELECT book_id
          FROM a_bkinfo.book_topics BT
    WHERE topic_id ='ORA' 
        OR topic_id ='MySQL');
SELECT b.book_id, b.title, COUNT(*) FROM books b
INNER JOIN book_topics bt ON (b.book_id = bt.book_id)
GROUP BY b.book_id, b.title
HAVING COUNT(*) = 2

this will work if you have only one row per book-topic relation in the book_topics. These pairs need to be unique as well. In case your data dont meet the requirements the more complicated query is needed.
UPDATE
As the book_id is the only unique identifier than this is the new version:

SELECT b.book_id FROM books b
INNER JOIN book_topics bt ON (b.book_id = bt.book_id)
GROUP BY b.book_id
HAVING COUNT(topic_id) = 2

Requirements are the same as above.

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