MySQL GROUP_CONCAT多个字段 [英] MySQL GROUP_CONCAT multiple fields
本文介绍了MySQL GROUP_CONCAT多个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可能没有脑子.
我想使用GROUP_CONCAT从数据库的两个字段返回一系列数字.到目前为止,我已经使用以下命令完成了此操作:
I want to return a series of numbers using GROUP_CONCAT from two fields in my database. I have done this so far using the following:
SELECT t_id,
CONCAT(GROUP_CONCAT(DISTINCT s_id),',',IFNULL(GROUP_CONCAT(DISTINCT i_id),'')) AS all_ids
FROM mytable GROUP BY t_id
这很好用,但是如果i_id为NULL,那么我当然会得到不必要的逗号.有没有更好的方法可以做到这一点,所以如果i_id为NULL,我不会以逗号结尾吗?
This works fine but if i_id is NULL then of course I get an unnecessary comma. Is there a better way to do this so I don't end up with a comma at the end if i_id is NULL?
推荐答案
您需要使用 CONCAT_WS 为避免NULL
值使用额外的comma
,请尝试以下操作:
You need to use CONCAT_WS to avoid extra comma
for NULL
values, try this:
SELECT t_id,
CONCAT_WS(',', GROUP_CONCAT(DISTINCT s_id),
GROUP_CONCAT(DISTINCT i_id)) AS all_ids
FROM mytable
GROUP BY t_id;
这篇关于MySQL GROUP_CONCAT多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文