Mysql group-concat输出错误

时间:2016-07-13 10:05:11

标签: mysql database

我的购买产品表

+------------+------------+
| productids | quantities |
+------------+------------+
| 1,3,4,5    | 1,1,1,1    |
| 2,3,4,5    | 1,1,1,1    |
+------------+------------+

我的产品表

 productsid | productsname                 |
+------------+-----------------------------+
|          1 | Phone                       |
|          2 | Laptop                      |
|          3 | Charger                     |
|          4 | Earphone                    |
|          5 | Camera                      |

我想根据purchaseproduct表中的productid获取产品名称

如下所示需要外出

Phone,Charger,Earphone,Camera (In row one)
Laptop,Charger,Earphone,Camera (In row two)

我尝试了以下声明和其他许多

select group_concat(p.productsname) from purchaseproducts as pp join products as p on find_in_set(p.productsid,pp.productids);

但我得到的输出是

 Phone,Charger,Earphone,Camera,Laptop,Charger,Earphone,Camera (All in one row)

如何实现我需要的输出?

1 个答案:

答案 0 :(得分:1)

您只需在DISTINCT

中使用GROUP_CONCAT即可
select pp.productsid , group_concat(DISTINCT p.productsname)
from purchaseproducts pp 
join products p 
 on find_in_set(p.productsid,pp.productids);
GROUP BY pp.productsid