SQL to join one table to another table multiple times? (Mapping products to categories)

前端 未结 4 1976
北海茫月
北海茫月 2021-02-04 19:54

Let\'s say I have a Product, Category, and Product_To_Category table. A Product can be in multiple categories.

    Product             


        
4条回答
  •  失恋的感觉
    2021-02-04 20:11

    SELECT p.name, cat_food.name, cat_flowers.name
    FROM
      product p
      left outer join  Product_to_category pc_food 
        on p.id = pc_food.Prod_id
      left outer join Category cat_food
        on pc_food.Cat_id = cat_food.id
        AND cat_food.name = 'Food'
      left outer join  Product_to_category pc_flowers
        on p.id = pc_flowers.Prod_id
      left outer join Category cat_flowers
        on pc_flowers.Cat_id = cat_flowers.id
        AND cat_flowers.Name = 'Flowers'
    

    It only works if you know the number of possible categories, to put them into columns. That's how (standard) SQL works, the number of columns is not dynamic.

提交回复
热议问题