最佳答案
假设我有三个不同的 MySQL 表:
表 products
:
id | name
1 Product A
2 Product B
表 partners
:
id | name
1 Partner A
2 Partner B
表 sales
:
partners_id | products_id
1 2
2 5
1 5
1 3
1 4
1 5
2 2
2 4
2 3
1 1
我希望获得一个表,其中行和产品中的合作伙伴作为列。到目前为止,我能得到这样的输出:
name | name | COUNT( * )
Partner A Product A 1
Partner A Product B 1
Partner A Product C 1
Partner A Product D 1
Partner A Product E 2
Partner B Product B 1
Partner B Product C 1
Partner B Product D 1
Partner B Product E 1
使用以下查询:
SELECT partners.name, products.name, COUNT( * )
FROM sales
JOIN products ON sales.products_id = products.id
JOIN partners ON sales.partners_id = partners.id
GROUP BY sales.partners_id, sales.products_id
LIMIT 0 , 30
但是我想换成这样的:
partner_name | Product A | Product B | Product C | Product D | Product E
Partner A 1 1 1 1 2
Partner B 0 1 1 1 1
问题是,我不能告诉我将有多少产品,因此需要根据 products 表中的行动态更改列号。
这个非常好的答案似乎不适用于 mysql: 从行值创建表列的可能性