如何实现子查询以选择与三个主题中的两个主题匹配的行?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何实现子查询以选择与三个主题中的两个主题匹配的行?相关的知识,希望对你有一定的参考价值。
我如何找到不带set运算符的完全覆盖三个不同SQL系统中的两个的书籍。我正在使用三个主题ID“ SSRV”,“ ORA”,“ mysql”,并且需要输出三个中的两个。例如,这本书可能有一个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');
答案
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
要求与上述相同。
以上是关于如何实现子查询以选择与三个主题中的两个主题匹配的行?的主要内容,如果未能解决你的问题,请参考以下文章