比方說,我有一個Product
,Category
和Product_To_Category
表。產品可以有多個類別。SQL將多個表連接到另一個表的多個表? (映射產品類別)
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)
這有幾個問題。
- 首先,我必須對每個預期類別重複此聯合;如果一個產品可以在8個類別中,我需要8個查詢。
- 其次,類別不是統一放在同一列中。例如,有時一種產品可能有'食物,花卉',另一種'鮮花,食物'。
有沒有人知道更好的方法來做到這一點?此外,這種技術是否有技術名稱?
我想你還需要添加GROUP BY,對吧? – meleyal 2009-07-24 14:29:23