mysql函数group_concat和find_in_set
id | score |
---|---|
1 | 55 |
2 | 22 |
2 | 25 |
3 | 33 |
3 | 34 |
4 | 46 |
4 | 48 |
group_concat
将多行数据按照某个条件合并成一行
select id,group_concat(score) from table group by id;
1 | 55 |
---|---|
2 | 22,25 |
3 | 33,34 |
4 | 46,48 |
dinstinct去重, separator ';'表示以分号为分隔符
select id,group_concat(distinct score separator ‘;') from table group by id;
1 | 55 |
---|---|
2 | 22;25 |
3 | 33;34 |
4 | 46;48 |
find_in_set
- 将一个字段的值拆分成多行,字段值需要以逗号隔开
string name=“a,b,c,d”; select * from table where find_in_set(id,name);
- 表示求表table中id值为a,b,c,d的数据,跟下面的sql一个含义
select * from table where id in('a','b','c','d');
- 可以用于码值配置
select * from table where find_in_set(id,(select itemno from code_library where codeno='a'));
- find_in_set(str,strlist) : str 要查询的字符串,strlist 需查询的字段,参数以”,”分隔,该函数的作用是查询字段(strlist)中是否包含(str)的结果.
select find_in_set(‘b', ‘a,b,c,d') from dual;
- 结果:2 b在strlist集合中2的位置
select find_in_set(‘a', ‘a,b,c,d') from dual;
- 结果:1 a在strlist集合中1的位置
select find_in_set(‘a', ‘b,c,d') from dual;
- 结果:0 strlist中不存在str,所以返回0。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论