我有一个书籍数据库,其中包含与书籍相关的类别和标签。我正在尝试构建一个过滤器,让用户可以过滤多个类别或标签,并查看包含这些标签或类别的书籍。它适用于单个类别或标记,但如果由于按书籍ID分组而存在多个标记或类别,则它会崩溃。
SELECT books.id as id,title, sub_title,medium_image_url,
amzn_url,amzn_review as review,SUBSTRING(kindle_price,2) as price,
IFNULL(ROUND(combined_ratings.love/(combined_ratings.love+combined_ratings.hate)*100), 0) AS rating ,
categories.category as category,GROUP_CONCAT(DISTINCT categories.id SEPARATOR ", ") as all_cats
FROM books
JOIN combined_ratings ON books.id = combined_ratings.book_id JOIN book_categories ON books.id = book_categories.book_id
JOIN categories ON book_categories.category_id = categories.id
WHERE (SUBSTRING(kindle_price,2) >= 0
AND SUBSTRING(kindle_price,2) <= 12
AND kindle_price <> "")
AND (IFNULL(ROUND(combined_ratings.love/(combined_ratings.love+combined_ratings.hate)*100), 0) >= 0
AND IFNULL(ROUND(combined_ratings.love/(combined_ratings.love+combined_ratings.hate)*100), 0) <= 100)
GROUP BY id
ORDER BY price ASC, rating DESC
我尝试过使用GROUP_CONCAT和HAVING,我只是读了一下IN(),但我尝试了它并没有用。我现在真正需要做的就是做一些像IN()的东西,任何建议?
编辑:我使用了这个并且能够获得单个类别的结果,但它只能运行一次...... 这有效......AND FIND_IN_SET( categories.id, '6' ) > 0
这不是
AND FIND_IN_SET( categories.id, '6' ) > 0 AND FIND_IN_SET( categories.id, '5' ) > 0
如果我能够解决这个问题,那就解决了我的问题。
答案 0 :(得分:0)
前一段时间有stackoverflow发布。请check it out。 另一种方法是每次创建临时表并将所有标签和类别放在那里,然后进行连接。
答案 1 :(得分:0)
我放弃了尝试单独使用JOIN并使用子查询。这对我有用,可能不太理想,但我现在可以根据需要过滤尽可能多的标签或类别。
SELECT id, title, author, image, sub_title, price, SUM(count) as count, rating FROM
(
SELECT books.id as id, title, author, medium_image_url as image, sub_title, kindle_price as price, IFNULL(ROUND(combined_ratings.love/(combined_ratings.love+combined_ratings.hate)*100), 0) as rating , COUNT( DISTINCT category_id ) AS count
FROM book_categories
JOIN books ON book_categories.book_id = books.id
JOIN authors ON books.author_id = authors.id
JOIN combined_ratings ON books.id = combined_ratings.book_id
WHERE category_id = 5
OR category_id = 6
OR category_id = 12
GROUP BY book_categories.book_id
HAVING count >= 3
UNION ALL
SELECT books.id as id, title, author, medium_image_url as image, sub_title, kindle_price as price, IFNULL(ROUND(combined_ratings.love/(combined_ratings.love+combined_ratings.hate)*100), 0) as rating , COUNT( DISTINCT tag_id ) AS count
FROM book_tags JOIN books ON book_tags.book_id = books.id
JOIN authors ON books.author_id = authors.id
JOIN combined_ratings ON books.id = combined_ratings.book_id
WHERE book_tags.tag_id = 22
GROUP BY book_tags.book_id HAVING count >= 1
)
as b1
WHERE (SUBSTRING(price,2) >= 0
AND SUBSTRING(price,2) <= 20 AND price <> '')
AND (rating >= 0 AND rating <= 100)
GROUP BY id
HAVING count = 4
ORDER BY price ASC,
rating DESC
这通过检查是否存在任何标准的结果然后计算标准匹配数来起作用。在外部查询中,我将两个联合查询相加,并确定这些计数的SUM()是否与参数总数相匹配。