0

所以我是 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_id:

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 表中提取所有书名。我不确定是否有更简单的方法可以做到这一点,但这就是我能想到的全部。

感谢任何可以提供帮助的人!

4

3 回答 3

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

这将选择所有具有三种类型之一的书籍。您的查询不清楚您是否想要在流派之间使用“或”或“和”,所以我假设“或”。

group by 使用了 MySQL 的一项功能,称为“隐藏列”。在这种情况下,它就像一个 distinct。

如果您需要所有三种类型的书籍,您可以这样做:

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
于 2012-09-24T21:44:23.017 回答
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
)
于 2012-09-24T21:44:49.000 回答
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

像 for = 一样交换,因为您没有使用通配符

我认为还有其他几种方法可以做到这一点,但没有一种方法能像你的努力那样容易理解,而且我不确定它们会表现得更好,所以除非表现很糟糕并且无法解决book_genres 的流派列上的索引,我个人会坚持这一点。

于 2012-09-24T22:03:54.973 回答