问题
I am attempting to do a tag system for selecting products from a database. I have read that the best way to achieve this is via a many-to-many relationship as using LIKE '%tag%' is going to get slow when there are a lot of records. I have also read this question where to match on multiple tags you have to do a join for each tag being requested.
I have 3 tables: shop_products, shop_categories and shop_products_categories. And I need to, for example, be able to find products that have both the tag "flowers" and "romance".
SELECT p.sku, p.name, p.path FROM shop_products p
LEFT JOIN shop_products_categories pc1 ON p.sku = pc1.product_sku
LEFT JOIN shop_categories c1 ON pc1.category_id = c1.id
LEFT JOIN shop_products_categories pc2 ON p.sku = pc2.product_sku
LEFT JOIN shop_categories c2 ON pc2.category_id = c2.id
WHERE c1.path = 'flowers' AND c2.path = 'romance'
This is the demo query I'm currently building to check it works before coding the relevant PHP for it and it works. But is this really the best way to do this? I find it hard to believe there isn't a better way to do this than to do a join for each tag searched. Thanks for any advice. :)
回答1:
No need to do multiple joins. If you need to match all tags, you can use an IN
clause with a subquery like this:
select p.sku, p.name, p.path
from shop_products p
where p.sku in (
select pc.product_sku
from shop_products_categories pc
inner join shop_categories c on pc.category_id = c.id
where c.path in ('flowers', 'romance')
group by pc.product_sku
having count(distinct c.path) = 2
)
Note that you will need to adjust the number 2 to be the number of unique tags you are matching on. Beware in case this is user-entered data and they enter the same tag twice.
回答2:
SELECT
p.sku, p.name, p.path
FROM
shop_products p
INNER JOIN
(
SELECT A.sku FROM
(
SELECT product_sku sku FROM shop_products_categories
WHERE category_id=(SELECT id FROM shop_categories WHERE path='flowers')
) A
INNER JOIN
(
SELECT product_sku sku FROM shop_products_categories
WHERE category_id=(SELECT id FROM shop_categories WHERE path='romance')
) B
USING (sku)
) flowers_and romance
USING (sku)
;
Make sure you have these indexes:
ALTER TABLE shop_categories ADD INDEX (path,id);
ALTER TABLE shop_categories ADD UNIQUE INDEX (path);
ALTER TABLE shop_products_categories ADD INDEX (product_sku,category_id);
来源:https://stackoverflow.com/questions/8824561/select-rows-with-multiple-tags-is-there-a-better-way