比方说,我有一个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)
Run Code Online (Sandbox Code Playgroud)
这有几个问题.
有谁知道更好的方法吗?此外,这种技术有技术名称吗?
我不知道你正在使用什么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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12878 次 |
| 最近记录: |