比方说,我有一个Product,Category和Product_To_Category表。一个产品可以在多个类别中。
Product
Category
Product_To_Category
Product Category Product_to_category ID | NAME ID | Name Prod_id | Cat_id ===================== ============ =================== 1| Rose 1| Flowers 1| 1 2| Chocolate Bar 2| Food 2| 2 3| Chocolate Flower 3| 1 3| 2
我想要一个SQL查询,它给我这样的结果
ProductName | Category_1 | Category_2 | Category_3 ======================================================= Rose | Flowers | | Chocolate Flower | Flowers | Food |
等等。
我能够做到这一点的最好方法是将一堆查询结合在一起。针对给定产品的每个预期类别数量查询一次。
select p.name, cat1.name, cat2.name from product p, (select * from category c, producttocategory pc where pc.category_id = c.id) cat1, (select * from category c, producttocategory pc where pc.category_id = c.id) cat2 where p.id = cat1.id and p.id = cat2.id and cat1.id != cat2.id union all select p.name, cat1.name, null from product p, (select * from category c, producttocategory pc where pc.category_id = c.id) cat1 where p.id = cat1.id and not exists (select 1 from producttocategory pc where pc.product_id = p.id and pc.category_id != cat1.id)
这有几个问题。
有谁知道更好的方法吗?另外,此技术是否有技术名称?
我不知道您正在使用什么RDBMS,但是在MySQL中,您可以使用GROUP_CONCAT:
SELECT p.name, GROUP_CONCAT(c.name SEPARATOR ', ') AS categories FROM product p JOIN product_to_category pc ON p.id = pc.product_id JOIN category c ON c.id = pc.category_id GROUP BY p.name ORDER BY p.name, c.name