2017-06-29 65 views
0

我正在使用MySQL數據庫。mysql map逗號分隔表查找新值的coumn值

我有一個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 

任何人都可以建議我如何從NEW_CUSTOMER_NO_FORMAT表做查找新格式映射CUST_INV_DET.CUSTOMER_NO

我知道我需要使用光標,但在光標下面的部分我無法如何映射,因爲它是一個逗號分隔值。

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' 
+0

你想映射多個NEW_CUSTOMER_NO到CUSTOMER_ID?與客戶ID 1一樣,您將擁有C1983-01,C1988-03,C1989-06。你想要一個選擇查詢還是想在其他表中插入/更新數據?也請添加有問題的表格結構。 –

+2

恭喜。所以現在你知道爲什麼存儲CSV是一個壞主意。 – Strawberry

+0

10年前有人得到了這個壞主意。 :D –

回答

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 
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 
+0

謝謝,但不包括逗號分隔值不是固定的。 –