在 MySQL 中拆分逗号分隔列表
要使用逗号分隔列表处理非规范化数据,有两种方法:加入或插入一张新桌子。
加入方法:
CREATE TEMP TABLE UNIQUE_MATERIALS AS SELECT DISTINCT TRIM(MATERIAL) AS MATERIAL FROM PART_TABLE;
SELECT p.part_id, m.material_id FROM PART_TABLE p JOIN UNIQUE_MATERIALS m ON p.MATERIAL LIKE CONCAT('%', m.MATERIAL, '%');
插入方法:
CREATE TABLE SPLIT_MATERIALS (part_id INT, material_id INT); INSERT INTO SPLIT_MATERIALS (part_id, material_id) VALUES (339, 1), (339, 2), (970, 2);
INSERT INTO SPLIT_MATERIALS (part_id, material_id) SELECT part_id, STR_TO_INT(TRIM(SUBSTR(MATERIAL, pos - 1, INSTR(MATERIAL, ',', pos) - pos + 1))) FROM PART_TABLE, (SELECT @pos := 1) AS vars, (SELECT INSTR(MATERIAL, ',')) AS tmp WHERE STR_TO_INT(SUBSTR(MATERIAL, @pos - 1, INSTR(MATERIAL, ',', @pos) - @pos + 1)) IS NOT NULL AND INSTR(MATERIAL, ',', @pos) > 0 GROUP BY part_id, STR_TO_INT(SUBSTR(MATERIAL, @pos - 1, INSTR(MATERIAL, ',', @pos) - @pos + 1)) ORDER BY part_id, SUBSTR(MATERIAL, @pos - 1, INSTR(MATERIAL, ',', @pos) - @pos + 1);
一旦新表已填充,可以将其与原始表连接以进行需要分隔的查询价值观。
以上是如何在 MySQL 中高效拆分逗号分隔列表?的详细内容。更多信息请关注PHP中文网其他相关文章!