如何在没有set运算符的情况下找到任何涵盖三种不同sql系统中的两种的书籍。我正在使用三个主题ID'SSRV','ORA','MySQL',需要输出任意三个中的2个。例如,本书可能有一个SSRV主题和一个ORA主题,但不是MySQL。这两个主题的任意两个组合足以通过我们的过滤器。 我想显示符合此测试的book_id和书名。我完全迷失了。
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
;
更新版本:
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');
答案 0 :(得分:0)
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
如果book_topics中每个图书 - 主题关系只有一行,这将有效。这些对也需要是唯一的。如果您的数据不符合要求,则需要更复杂的查询
的更新强>
由于book_id是唯一的唯一标识符,因此是新版本:
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
要求与上述相同。