可以说我有三个不同的MySQL表:
表产品:
id | name
1 Product A
2 Product B
表合作伙伴:
id | name
1 Partner A
2 Partner B
表销售额:
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表中的行动态更改.