Select rows with multiple tags… is there a better way?

前端 未结 2 852
甜味超标
甜味超标 2021-01-22 11:34

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%

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-22 12:22

    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);
    

提交回复
热议问题