mysql case when 碰上中文字符串

碰上中文字符串

大家好
我有一个表如下
publications id | publications field id| publications description
1000 | 1 | 小名
1000 | 2 | 2014
1000 | 4 | aa@...
1000 | 6 | 123-456-789
1012 | 1 | 阿花

我想把它结合成这样
publications id | publications description
1000 |小名,2014,NULL,aa@..,NULL,123-456-789
1012 |阿花, NULL, NULL, NULL, NULL, NULL

目前是使用casewhen
SELECT publications id,
case publications field id when ‘1’ then publications description else 'null'end as column1,
case publications field id when ‘2’ then publications description else 'null'end as column2,
case publications field id when ‘3’ then publications description else 'null'end as column3,
case publications field id when ‘4’ then publications description else 'null'end as column4,
case publications field id when ‘5’ then publications description else 'null'end as column5,
case publications field id when ‘6’ then publications description else 'null'end as column6
FROM publications
Group by publications id

结果却产出
publications id | publications description
1000 | NULL, NULL, NULL, NULL, NULL, NULL
1012 |阿花, NULL, NULL, NULL, NULL, NULL

竟然只有出现一次阿花,其他都不见了??
到底是哪里写错呢?是因为中文吗?还是><?
最新回答
爱哭的小鬼

2024-10-23 02:41:14

恩。。。感觉不大对呢。
小名,2014,NULL,aa@..,NULL,123-456-789
是在一个字段里吧,按照你下面的写法,好像是放到了很多的字段里,你确定这个是你要的?
你用group_concat函数试试,应该能达到你上面的需求。(就是没有null)
至于你上面的问题,你的语句去掉group查出来的结果应该是
1000 小名 null null null null null
1000 null 2014 null null null null
。。。。。。。。。
你在group聚合的时候,没有指令上面的字段和下面的字段用什么方式结合,就是说“小名+null”用什么方式结合,也就是说在case when的外层少了一个聚合函数,不过按照这个写法,这个聚合函数是什么我还真不清楚,因为不管怎么聚和每个字段都会出现一堆的NULL,跟你的要求不符。
比较简单的解决办法,个人建议补齐1-6,没有就写null,这样查询的话用group_concat就行。
如果不加,个人感觉就比较麻烦了。
先用null合并,就是不加单引号的null,聚合后在显示的时候用上ifnull
追问

是的我想存成一个字段里!

小名,2014,NULL,aa@..,NULL,123-456-789


而且如你所说

现在真是这样

1000   小名    null  null  null   null null

1000   null    2014 null  null   null null

刚也在尝试groupby 完全如你预期无法结合


追答
你把
case publications field id when ‘1’ then publications description else 'null'end as column1,
改为
case publications field id when ‘1’ then publications description else null end as column1,
其他几个都改,这样,应该就是
1000 小名 空 空 空 空 空
1000 空 2014 空 空 空 空
。。。。。
然后你用在外面套一层group_concat试试看看出来的结果是什么,我说的是每个字段的结果,
group_concat(case publications field id when ‘1’ then publications description else null end) as column1
你看看字段1-6出的结果是什么。
如果是1000 小名 2014 空 。。。。。那就好了
但如果是1000 小名,,, ,2014,,,, ,,,,,, 。。。。。那就麻烦了。
这时别忘了groupby啊
追问
谢谢你阿  真是对了!
改成null 另加group_concat就对啦!
不过现在就只好乖乖写70行了..
追答
那没办法啊,对了别忘了还要用到ifnull,不然null不显示null这个字符的。呵呵
追问
谢谢你这么仔细教学阿~~~:D 料事如神