在MySQL

时间:2017-02-27 08:33:49

标签: mysql stored-procedures split concatenation concat

我在MySQL中有以下表格

表1:
c1 ids
A1 3 | 5 | 2
A2 1 | 2
A3 3
A4 1 | 2 | 3 | 4 | 5
A5 2 | 4 | 1 | 3

表2:
身份证号码 1 AA
2 ABERT
3 CDE
4 XXWQ
5 Y

我想将tb1.ids = tb2.id上的两个表连接为从表1中拆分所有id,然后用它们的名称替换,然后重新连接。

输出

3 | 5 | 2 - > CDE | Y | ABERT
1 | 2 - > AA | ABERT

我使用以下代码拆分字符串。

CASE WHEN tb1.ids LIKE '%|%'THEN SUBSTRING_INDEX( `tb1.ids` , '|', 1 ) ELSE tb1.ids END AS id1,
CASE WHEN tb1.ids LIKE '%|%|%' THEN SUBSTRING_INDEX(SUBSTRING_INDEX( `tb1.ids` , '|', 2 ),'|',-1) WHEN tb1.ids LIKE '%|%' THEN SUBSTRING_INDEX( `tb1.ids` , '|', -1 )ELSE '' END AS id2,
CASE WHEN tb1.ids LIKE '%|%|%|%' THEN SUBSTRING_INDEX(SUBSTRING_INDEX( `tb1.ids` , '|', 3 ),'|',-1) WHEN tb1.ids LIKE '%|%|%' THEN SUBSTRING_INDEX( `tb1.ids` , '|', -1 ) ELSE '' END AS id3,
CASE WHEN tb1.ids LIKE '%|%|%|%|%' THEN SUBSTRING_INDEX(SUBSTRING_INDEX( `tb1.ids` , '|', 4 ),'|',-1) WHEN tb1.ids LIKE '%|%|%|%' THEN SUBSTRING_INDEX( `tb1.ids` , '|', -1 ) ELSE '' END AS id4,
CASE WHEN tb1.ids LIKE '%|%|%|%|%|%' THEN SUBSTRING_INDEX(SUBSTRING_INDEX( `tb1.ids` , '|', 5 ),'|',-1) WHEN tb1.ids LIKE '%|%|%|%|%' THEN SUBSTRING_INDEX( `tb1.ids` , '|', -1 ) ELSE '' END AS id5

2 个答案:

答案 0 :(得分:1)

如果您无法更改架构,可以使用LIKE加入,并将名称与GROUP_CONCAT合并:

select t1.c1, t1.ids, group_concat(t2.name separator '|') as names
from table1 t1
join table2 t2
  on concat('|', t1.ids, '|') like concat('%|', t2.id, '|%')
group by t1.c1, t1.ids

结果:

╔════╦═══════════╦═════════════════════╗
║ c1 ║    ids    ║        names        ║
╠════╬═══════════╬═════════════════════╣
║ A1 ║ 3|5|2     ║ CDE|ABERT|Y         ║
║ A2 ║ 1|2       ║ ABERT|AA            ║
║ A3 ║ 3         ║ CDE                 ║
║ A4 ║ 1|2|3|4|5 ║ CDE|Y|ABERT|AA|XXWQ ║
║ A5 ║ 2|4|1|3   ║ XXWQ|CDE|ABERT|AA   ║
╚════╩═══════════╩═════════════════════╝

演示:http://rextester.com/XHUP28245

如果您需要根据t1.ids订购名称,一种可能的方法是在GROUP_CONCAT中使用ORDER BY的LOCATE函数:

select t1.c1, t1.ids, group_concat(
    t2.name
    order by locate(concat('|', t2.id, '|'), concat('|', t1.ids, '|'))
    separator '|'
) as names
from table1 t1
join table2 t2
  on concat('|', t1.ids, '|') like concat('%|', t2.id, '|%')
group by t1.c1, t1.ids

结果:

╔════╦═══════════╦═════════════════════╗
║ c1 ║    ids    ║        names        ║
╠════╬═══════════╬═════════════════════╣
║ A1 ║ 3|5|2     ║ CDE|Y|ABERT         ║
║ A2 ║ 1|2       ║ AA|ABERT            ║
║ A3 ║ 3         ║ CDE                 ║
║ A4 ║ 1|2|3|4|5 ║ AA|ABERT|CDE|XXWQ|Y ║
║ A5 ║ 2|4|1|3   ║ ABERT|XXWQ|AA|CDE   ║
╚════╩═══════════╩═════════════════════╝

演示:http://rextester.com/WIUQ61685

答案 1 :(得分:1)

在表格中存储分隔字段几乎总是一个坏主意。

但是,如果字段用逗号分隔,则可以使用FIND_IN_SET函数。如果绝望,您可以使用REPLACE将分隔符更改为FIND_IN_SET函数中的逗号: -

SELECT a.c1,
        a.ids,
        GROUP_CONCAT(b.name SEPARATOR '|')
FROM Table1 a
INNER JOIN Table2 b
ON FIND_IN_SET(b.id, REPLACE(a.ids, '|', ','))
GROUP BY a.c1,
        a.ids