在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中文網其他相關文章!