我有两张桌子
Topic
----------------------
id title
----------------------
1 Loops
2 Control Structure
3 Basics
Chapters
------------------------------------------------------
id book_id topic_id chapter_number
------------------------------------------------------
1 1 1 1
2 1 2 2
3 1 3 3
4 2 1 5
5 2 3 2
6 3 3 1
搜索主题时,我想展示包含这些主题章节的book_ids。
具有主题1和2的Book_ids: 1
具有主题3的Book_Ids: 1,2,3
包含主题1和3的BookIds: 1
这是我的疑问:
SELECT DISTINCT chapter.book_id FROM chapter Inner Join topic ON topic.id = chapter.topic_id WHERE topic.id IN ( '1,3');
但它返回Book_ids:1和3,而它应该只返回1.看来我的查询返回union,它应该返回一个交集。
有人可以帮我修理吗?
答案 0 :(得分:0)
这是SQLFiddle demo。只需将此查询中的'1,3'
替换为您需要的任何章节:
select book_id from Chapters
where FIND_IN_SET(topic_id,'1,3')
group by book_id
having
count(*) =
(length('1,3')-length(replace('1,3',',',''))+1)
答案 1 :(得分:0)
在“IN”中,您应该使用逗号分隔值。使用您的查询,您希望看到包含'1,3'字符串值而不是1或2或3个int值的子集。正确的查询在
之下SELECT DISTINCT chapter.book_id
FROM chapter
Inner Join topic ON topic.id = chapter.topic_id
WHERE topic.id IN (1,3);
或者如果您只想要ID
SELECT DISTINCT book_id
FROM Chapters
WHERE topic_id IN (1,3);