如何在mysql中使用split函数或在不同的列中存储split值?

axkjgtzd  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(524)
  1. String x "3_SJ454FH";

我想在mysql的一列中存储'3'(在u3;之前),在另一列中存储'sj454fh'(在3;之后)。我尝试过在存储过程中使用substring\ u index函数,但没有成功。那么,有没有办法像这样在存储过程中存储值呢。?

  1. CREATE DEFINER=`root`@`localhost` PROCEDURE `insert_csv`(_list MEDIUMTEXT)
  2. BEGIN
  3. DECLARE _next TEXT DEFAULT NULL;
  4. DECLARE _nextlen INT DEFAULT NULL;
  5. DECLARE _value TEXT DEFAULT NULL;
  6. iterator:
  7. LOOP
  8. -- exit the loop if the list seems empty or was null;
  9. -- this extra caution is necessary to avoid an endless loop in the proc.
  10. IF LENGTH(TRIM(_list)) = 0 OR _list IS NULL THEN
  11. LEAVE iterator;
  12. END IF;
  13. -- capture the next value from the list
  14. SET _next = SUBSTRING_INDEX(_list,'_',1);
  15. -- save the length of the captured value; we will need to remove this
  16. -- many characters + 1 from the beginning of the string
  17. -- before the next iteration
  18. SET _nextlen = LENGTH(_next);
  19. -- trim the value of leading and trailing spaces, in case of sloppy CSV strings
  20. SET _value = TRIM(_next);
  21. -- insert the extracted value into the target table
  22. INSERT INTO t1 (c1) VALUES (_value);
  23. -- rewrite the original string using the `INSERT()` string function,
  24. -- args are original string, start position, how many characters to remove,
  25. -- and what to "insert" in their place (in this case, we "insert"
  26. -- an empty string, which removes _nextlen + 1 characters)
  27. SET _list = INSERT(_list,1,_nextlen + 1,'');
  28. END LOOP;
  29. END

输出:

  1. id|c1
  2. -----------
  3. 1 |3
  4. -----------
  5. 2 |SJ454FH
  6. -----------

我试过这个代码,但它存储在下一行。

8ftvxx2r

8ftvxx2r1#

您可以将以下查询的逻辑与into结合使用,用所需的值填充两个变量,然后在单独的调用中插入它们。

  1. SELECT LEFT("3_SJ454FH", INSTR("3_SJ454FH", "_")-1) AS Prefix,
  2. MID("3_SJ454FH", INSTR("3_SJ454FH", "_")+1, LENGTH("3_SJ454FH")) AS Tail

相关问题