我有这个架构:
table_products: product_id, name, price,
table_categories: category_id, name,
table_categories_products:category_id,product_id
我想列出我的数据库中的所有产品,包括每个产品的所有类别。
实际上我使用这个查询:
SELECT p.id, p.name, p.price, GROUP_CONCAT(c.category_id, ';', c.name SEPARATOR ',')
FROM table_products
LEFT JOIN table_categories_products tcp ON tcp.product_id=p.product_id
LEFT JOIN table_categories c ON c.category_id=p.product_id
GROUP BY p.id
问题是一个产品可能属于无限类别,而 group_concat 有大小限制。
更新
我已经考虑过增加“group_concat_max_len”的选项,但不允许无限字符串
最佳答案
您可以通过以下方式更改 group_concat 的最大大小:
SET [GLOBAL | SESSION] group_concat_max_len = val;
默认为1024,最大可设置值为1073741824
至少医生是这么说的: http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat
关于MYSQL 列出所有类别的所有产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37411323/