假设我有一个
这样做存在几个问题。
Product
,Category
和Product_To_Category
表。一个产品可以属于多个类别。
Product Category Product_to_category ID | NAME ID | Name Prod_id | Cat_id ===================== ============ =================== 1| 玫瑰 1| 花卉 1| 1 2| 巧克力棒 2| 食品 2| 2 3| 巧克力花 3| 1 3| 2
我想要一个SQL查询,使我得到以下结果:
ProductName | Category_1 | Category_2 | Category_3 ======================================================= 玫瑰 | 花卉 | | 巧克力花 | 花卉 | 食品 |
等等。
我能够得到这个的最好方法是将一堆查询联合在一起;对于每个产品预期的类别数量进行一次查询。
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)
这样做存在几个问题。
- 首先,我必须为每个预期类别重复此联合查询;如果一个产品可以属于8个类别,我需要8个查询。
- 其次,类别没有统一放置在同一列中。例如,有时一个产品可能有“食品、花卉”,而另一次则是“花卉、食品”。