mysql comma-separated id to comma-separated name

Today, I am    dealing with a requirement. The table field stores the code separated by commas , and the other table stores the code_name corresponding to the code. Now it is required to convert the code of the field in the table into code_name and separate it with commas. The form and table field same.

Requirement description:​

The effect achieved:

 

In order to solve this problem, I thought of the split function written in sqlserver before, and I was going to take it and modify it. It turned out that the syntax of the two create functions did not work. I tried to modify it and found that mysql does not seem to support table variables. After this is over, the comma-separated code cannot be sent out in the form of a table to match. Then go to the Internet to find the split function of mysql and find out why it is so troublesome. To write a function, you must first create two functions to prepare the ground. decisively gave up.

Then I found some information to solve this problem with the functions that come with mysql

1. INSTR function (INSTR is equivalent to the CharIndex function of sqlserver)

INSTR(fieldname, string)

This function returns the position of the string in the content of a field, returns 0 if the string is not found, otherwise returns the position (starting from 1)

select GROUP_CONCAT(code_name) from t_fix_code

where INSTR((select engine_number from t_inventory_tmp where id =1 ),code)>0 and length(code)=8

Although it seems that it can be used, there is a problem that if the codes separated by commas correspond to a code_name at different lengths, the matching results will increase. There is also an instr function subquery that can only return one row and cannot match the entire table. However, there is still a problem that can be solved.

just re-applied INSTR

select a.engine_number,GROUP_CONCAT(b.code_name)

from t_inventory_tmp a

join t_fix_code b

on INSTR(a.engine_number,b.code)>0 and length(code)=8

group by a.engine_number

这个解决了问题但是条件里面有一条length(code) = 8 简称我必须要先明确code的长度并且还要统一长度,负责就会出现匹配结果变多,还是很尴尬。

2、FIND_IN_SET函数

假如字符串str在N子链以逗号分割组成的字符串列表strlist 中,则返回值的范围在1到N之间。 如果str不在strlist 或strlist 为空字符串,则返回值为0。

关于FIND_IN_SET用法细节我还是不太清楚,有时间再了解下。

select b.engine_number,GROUP_CONCAT(code_name) as tran_name

from t_fix_code a,t_inventory_tmp b

where FIND_IN_SET(a.code,b.engine_number) > 0

group by b.engine_number

或者

select b.engine_number,GROUP_CONCAT(code_name) as tran_name

from t_fix_code a

join t_inventory_tmp b ON FIND_IN_SET(a.code,b.engine_number) > 0

group by b.engine_number


Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326860652&siteId=291194637