如何拆分逗号分隔的记录串并在MySQL中顺序排列?

时间:2016-07-21 09:30:59

标签: mysql select

我想要一个MySQL查询来从下面的表中单独选择记录

   ID  AgentID    Name   Return Date
   1   1,2,3       A     2016-05-22,2016-02-1,2016-1-15
   2   2,4         B     2016-03-22,2016-04-1

期待答案

ID  AgentID    Name   Return Date
1    1          A     2016-05-22
1    2          A     2016-02-1
1    3          A     2016-1-15
2    2          B     2016-03-22
2    4          B     2016-04-1

3 个答案:

答案 0 :(得分:2)

您可以使用MySQL SUBSTRING_INDEX()。它将在指定的分隔符出现次数之前从给定的逗号分隔字符串返回子字符串。

试试这个,似乎工作正常:

SELECT ID
       ,SUBSTRING_INDEX(SUBSTRING_INDEX(t.AgentID, ',', n.n), ',', -1) Agent
       ,Name
       ,SUBSTRING_INDEX(SUBSTRING_INDEX(t.Return_Date, ',', n.n), ',', -1) Return_Date
FROM table1 t CROSS JOIN 
 (
   SELECT a.N + b.N * 10 + 1 n
   FROM 
     (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
    ,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
   ORDER BY n
  ) n

WHERE n.n <= 1 + (LENGTH(t.Return_Date) - LENGTH(REPLACE(t.Return_Date, ',', '')))
ORDER BY ID;

检查一下.. SQL Fiddle HERE

有关进一步研究,请转到MySQL Split String Function

答案 1 :(得分:0)

如果您在tblA中的值,并且您希望插入到tblB而不是像此

这样的查询
insert into tblB (date) select date from tblA;

答案 2 :(得分:-1)

INSERT INTO second_table ( 
      Field_1, 
      Field_2, 
      Field_3) 
SELECT Field_1, 
      Field_2, 
      Field_3 
      FROM first_table;