1.1 长度限制
GROUP_CONCAT
有长度限制,默认1024,如果你尝试连接的字符串超过这个长度,结果就会被截断。
show VARIABLES Like 'group_concat_max_len';
可以通过以下方式修改这个配置:
SET SESSION group_concat_max_len = 10000;
或
SET GLOBAL group_concat_max_len = 10000;
或者修改 MySQL 的配置文件:
group_concat_max_len = 10000
或者修改数据库连接:
sessionVariables=group_concat_max_len=10000
1.2 无中生有
selectblc.id as balanceId,GROUP_CONCAT(distinct rel.fund_code) fundCodes
fromt_balance_margin blc
inner join t_balance_fund_relation rel onrel.is_delete = 0and rel.balance_id = blc.idand rel.balance_type = 3
whereblc.id = 0
以上 SQL,由于 bic.id 是不可能等于0的,所以结果集中应该没有数据。但是,当你使用 GROUP BY 语句时,MySQL 会为每个组返回一行。如果没有匹配的行,MySQL 仍然会返回一行,但所有的列都会是 NULL。
所以本次查询的结果如下:
balanceId | fundCodes |
---|---|
NULL | NULL |
显然这会导致最终的结果集中出现一个所有字段都 NULL 的元素,造成可能的 NPE。
解决办法:在查询的最后添加一个HAVING子句,检查某个非NULL的列。
selectblc.id as balanceId,GROUP_CONCAT(distinct rel.fund_code) fundCodes
fromt_balance_margin blc
inner join t_balance_fund_relation rel onrel.is_delete = 0and rel.balance_id = blc.idand rel.balance_type = 3
whereblc.id = 0
having blc.id is not null