【发布时间】:2010-10-20 15:32:10
【问题描述】:
假设我有一个Product、Category 和Product_To_Category 表。一个产品可以属于多个类别。
我想要一个 SQL 查询,它会给我这样的结果
产品名称 |类别_1 |类别_2 |类别_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 个查询。
- 第二,类别不统一放在同一列。例如,有时某个产品可能包含“食物,鲜花”,有时可能包含“鲜花,食物”。
有人知道更好的方法吗?另外,这种技术有技术名称吗?
【问题讨论】: