分隔字符串列表并用mysql中的新值替换相同的列表 我在table_1表中有以下数据 table_1(当前保存的结构)
code value
12_A ["A","B","C","D"]
12_B ["E","F","G","H"]
12_3 ["I","J","K","L"]
但是每个代码都有不同的值和不同的描述。像::
code value description
12_A A Apple
12_A B Ball
12_A C Cat
12_A D Dog
12_B E Eagle
12_B F Flag
. . .
. . .
. . .
我必须将值列表与table_1和。分开 需要再次保存在同一个表中,即table_1(在此结构中)::
code value
12_A ["Apple","Ball","Cat","Dog"]
12_B ["Eagle","Flag",.......]
12_3 [......................]
答案 0 :(得分:4)
您可以使用GROUP_CONCAT()
:
UPDATE Table1 s
SET s.value = (SELECT t.code,CONCAT('["',
GROUP_CONCAT(t.description ORDER BY t.description SEPARATOR '","'),
']')
FROM Table_With_val t
WHERE t.code = s.code
AND s.value LIKE CONCAT('%"',t.value,'"%'))
您没有提供任何结论性信息,我假设您提供的第二个数据样本是现有表格,而table1是您要更新的表格。
注意:这是一个糟糕数据库结构!它最具挑战性的是将来会出现问题,尤其是在需要进行连接时。我强烈建议您规范化您的数据并将每个描述和值存储在自己的记录中。
答案 1 :(得分:4)
你可以创建一个函数,你可以将你的字符串列表作为参数传递给你的例子 [" A"," B"," C& #34;," D"] 将成为参数。该函数将分解字符串并将根据描述连接描述。您可以使用的功能示例如下:
DELIMITER $$
DROP FUNCTION IF EXISTS codeToDesc$$
CREATE FUNCTION codeToDesc(commaSeperatedCodeList TEXT) RETURNS TEXT CHARSET utf8
BEGIN
DECLARE finalString TEXT;
DECLARE inputCodeList TEXT;
DECLARE codeName VARCHAR(255);
DECLARE codecount BIGINT(5);
SET finalString='';
SET inputCodeList = REPLACE(REPLACE(REPLACE(commaSeperatedCodeList,'[',''),']',''),'"','');
DROP TEMPORARY TABLE IF EXISTS test.code_table;
DROP TEMPORARY TABLE IF EXISTS test.code_count;
CREATE TEMPORARY TABLE test.code_table (CODE VARCHAR(255));
CREATE TEMPORARY TABLE test.code_count (countNo BIGINT(11));
INSERT INTO test.code_count(countNo) SELECT(LENGTH(inputCodeList)-LENGTH(REPLACE(inputCodeList,',','')) + 1);
BEGIN
DECLARE table_cursor CURSOR FOR SELECT countNo FROM test.code_count;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET codecount = (SELECT countNo FROM test.code_count ORDER BY countNo ASC LIMIT 1);
OPEN table_cursor;
readLoop1: LOOP
FETCH table_cursor INTO codecount;
IF codecount=0 THEN
LEAVE readLoop1;
END IF;
SET codeName=(SELECT SUBSTRING_INDEX(inputCodeList,',',1));
INSERT INTO test.code_table(CODE) SELECT codeName;
SET inputCodeList=(SELECT TRIM(BOTH ',' FROM REPLACE(inputCodeList,codeName,'')));
INSERT INTO test.code_count(countNo) SELECT codecount-1;
SET codeName='';
END LOOP;
CLOSE table_cursor;
END;
-- use your code and description here, i guess those should be fixed
SELECT CONCAT('["',REPLACE(GROUP_CONCAT(CASE WHEN CODE='A' THEN 'Apple'
WHEN CODE = 'B' THEN 'Ball'
WHEN CODE = 'C' THEN 'Cat'
WHEN CODE = 'D' THEN 'Dog'
ELSE '' END),',','","'),'"]') INTO finalString FROM test.code_table;
RETURN finalString;
END$$
DELIMITER ;
试试这个,如果您发生任何问题,请与我们联系。