mysql map逗号通过表查找分隔新值的coumn值

时间:2017-06-29 03:37:49

标签: mysql sql

我正在使用MySQL数据库。

我有一个CUST_INV_DET表格,其中包含以下格式的数据

---------------------------
CUSTOMER_ID   CUSTOMER_NO
---------------------------
     1        1983,1988,1989
     2        2014,2011,2010
     3        3012,3059,3045 
---------------------------

还有另一张桌子。 NEW_CUSTOMER_NO_FORMAT

--------------------------------------
OLD_CUSTOMER_NO      NEW_CUSTOMER_NO
--------------------------------------
1983                    C1983-01
1988                    C1988-03
1989                    C1989-06
2014                    C2014-01
2011                    C2011-02
2010                    C2010-02
3012                    C3012-03
3059                    C3059-23
3045                    C3045-09

有人可以建议我如何通过从CUST_INV_DET.CUSTOMER_NO表格进行查找,以新格式映射NEW_CUSTOMER_NO_FORMAT

我知道我需要使用光标但是在光标下面的部分我无法如何映射,因为它是逗号分隔值。

我是否需要在NO_MORE_DATA = 0中再添加一个游标?

IF (NO_MORE_DATA = 0) THEN

  //MAP OLD TO NEW FORMAT HERE

END IF;

以下是插入脚本

CREATE TABLE CUST_INV_DET(
  CUSTOMER_ID INT(11) AUTO_INCREMENT PRIMARY KEY, 
  CUSTOMER_NO VARCHAR(500)
);

INSERT INTO CUST_INV_DET(CUSTOMER_NO) VALUES
('1983,1988,1989'),
('2014,2011,2010'),
('3012,3059,3045');

CREATE TABLE NEW_CUSTOMER_NO_FORMAT (
  OLD_CUSTOMER_NO VARCHAR(500),
  NEW_CUSTOMER_NO VARCHAR(500)
);

INSERT INTO NEW_CUSTOMER_NO_FORMAT VALUES
('1983','C1983-01'),
('1988','C1988-03'),
('1989','C1989-06'),
('2014','C2014-01'),
('2011','C2011-02'),
('2010','C2010-02'),
('3012','C3012-03'),
('3059','C3059-23'),
('3045','C3045-09');

以下是我要找的最终输出

CUSTOMER_ID           CUSTOMER_NO                    
1                     'C1983-01,C1988-03,C1989-06'
2                     'C2014-01,C2011-02,C2010-02'
3                     'C3012-03,C3059-23,C3045-09'

2 个答案:

答案 0 :(得分:0)

select 
CUSTOMER_ID, 
substring(Customer_no,0,charindex(',',Customer_no,1)) col1,
substring(Customer_no,charindex(',',Customer_no,1) + 1,charindex(',',Customer_no,1)-1) col2,
substring(Customer_no,charindex(',',Customer_no,1) + len(substring(Customer_no,charindex(',',Customer_no,1) + 1,charindex(',',Customer_no,1)-1) )+2,charindex(',',Customer_no,1)-1) col3
into #Temp2
from CUST_INV_DET

答案 1 :(得分:0)

SELECT T. CUSTOMER_ID,
       NCD1.NEW_CUSTOMER_NO + ',' + NCD2.NEW_CUSTOMER_NO + ',' + NCD3.NEW_CUSTOMER_NO
FROM #Temp2 T
INNER JOIN NEW_CUSTOMER_NO_FORMAT NCD1 ON NCD1.OLD_CUSTOMER_NO = T.col1
INNER JOIN NEW_CUSTOMER_NO_FORMAT NCD2 ON NCD2.OLD_CUSTOMER_NO = T.col2
INNER JOIN NEW_CUSTOMER_NO_FORMAT NCD3 ON NCD3.OLD_CUSTOMER_NO = T.col3