所以我是MySQL新手,遇到了一些麻烦。我有一个名为book_genres的表,另一个名为books。
book_genres
+-------+---------+
|book_id| genre |
+-------+---------+
| 1 | Horror |
| 1 | Comedy |
| 2 | Romance |
| 2 | Comedy |
+-------+---------+
books
+-------+---------+
|book_id| title |
+-------+---------+
| 1 | A Book |
| 2 | B Book |
| 3 | C Book |
+-------+---------+
我使用以下命令来提取所有具有3种选定类型的book_ids:
SELECT DISTINCT a.book_id, b.genre AS genre1, c.genre AS genre2, d.genre AS genre3
FROM book_genres a
JOIN book_genres b ON a.book_id = b.book_id AND b.genre LIKE 'Romance'
JOIN book_genres c ON a.book_id = c.book_id AND c.genre LIKE 'Action'
JOIN book_genres d ON a.book_id = d.book_id AND d.genre LIKE 'Comedy'
GROUP BY book_id
我想要做的是现在使用此搜索中找到的book_ids从books表中提取所有书名。我不确定是否有更简单的方法可以做到这一点,但这就是我能想到的。
感谢所有可以提供帮助的人!
答案 0 :(得分:1)
我认为这可能是一种更好的方法:
select b.*
from books b join
book_genres bg
on b.bookid = bg.bookid
where bg.genre in ('Romance', 'Action', 'Comedy')
group by b.book_id
这将选择所有具有三种类型之一的书籍。您的查询不清楚您是否想要“或”或“和”之间的类型,所以我假设“或”。
该组使用MySQL的一个名为“隐藏列”的功能。在这种情况下,它就像一个独特的。
如果你需要所有三种类型的书籍,你可以这样做:
select b.*
from books b join
(select book_id
from book_genre
group by book_id
having max(case when genre = 'Romance' then 1 else 0 end) > 0 and
max(case when genre = 'Action' then 1 else 0 end) > 0 and
max(case when genre = 'Comedy' then 1 else 0 end) > 0
) allg
on b.book_id = allg.book_id
答案 1 :(得分:0)
您可以执行子查询,如下所示:
SELECT books.title
FROM books
WHERE books.book_id
IN (
SELECT
a.book_id
FROM
book_genres a
JOIN book_genres b ON a.book_id = b.book_id AND b.genre LIKE 'Romance'
JOIN book_genres c ON a.book_id = c.book_id AND c.genre LIKE 'Action'
JOIN book_genres d ON a.book_id = d.book_id AND d.genre LIKE 'Comedy'
GROUP BY book_id
)
答案 2 :(得分:0)
嗯,你会因为快速而肮脏的答案而踢你自己
SELECT DISTINCT a.book_id, a.book_title,
b.genre AS genre1, c.genre AS genre2, d.genre AS genre3
FROM book_genres a
JOIN book_genres b ON a.book_id = b.book_id AND b.genre = 'Romance'
JOIN book_genres c ON a.book_id = c.book_id AND c.genre = 'Action'
JOIN book_genres d ON a.book_id = d.book_id AND d.genre = 'Comedy'
GROUP BY book_id
因为你没有使用外卡而被忽略了
我认为还有其他一些方法可以做到这一点,但是没有一种方法可以像你的努力那样容易理解,而且我很不确定它们会表现得更好,所以除非表现是可怕的而且不能用book_genres的类型栏索引来解决,我个人坚持这一点。