2016-10-04 37 views
0

我的數據庫包含演講人信息(名稱,地理位置,專業)表。我需要使用PHP腳本定期從CSV文件更新表格。我遇到的麻煩是專業被存儲爲逗號分隔列表。如果演講者的表格條目已經存在,我想從CSV文件添加專業,除非該專業已經在列表中。這是我想出了(可能是怪誕)SQL語句(由我的PHP腳本通過CSV文件中讀取生成):MySQL LOCATE函數不適用於IF塊

INSERT INTO speakers (email, last_name, first_name, specialty, country_code, 
    iot, imt, role, num_responses, sat_total) 
VALUES ('[email protected]', 'Last', 'First', 'Computers,', '777', 
'AP', 'ASEAN', 'Big Shot', 15, 1500) 
    ON DUPLICATE KEY UPDATE num_responses = (num_responses + 15), 
    sat_total = (sat_total + 1500), 
    specialty = CONCAT(specialty, 
    (IF(LOCATE(specialty, 'Computers,') > 0, '', 'Computers,'))) 

我的這個讀是,如果LOCATE找到「計算機」字符串中的現有的專業欄,它應該返回一個空字符串到CONCAT功能。但是,每次運行該命令時,LOCATE都會返回'Computers'字符串,因此在第二次運行後,特殊表條目字符串看起來像'Computers,Computers','Computers,Computers,Computers',在第三個,等等......提前感謝您的幫助。

+0

我很懷疑你想這樣的編程:由於上評論說,找到參數應以產生所需的輸出調換創建表ABC (\t專業VARCHAR(100)NOT NULL ); ('computers'),('d,computers'); (專業,(IF(LOCATE(專業,'Computers,')> 0,'','Computers,')))from abc; – Drew

+1

我建議你看一下[Junction Tables](http://stackoverflow.com/a/32620163),並對其進行編碼以獲得性能和理智 – Drew

+1

這是另一種方式:LOCATE('Computers',專業) – Jayvee

回答

1

出於文檔目的。

INSERT INTO speakers (email, last_name, first_name, specialty, country_code, 
    iot, imt, role, num_responses, sat_total) 
VALUES ('[email protected]', 'Last', 'First', 'Computers,', '777', 
'AP', 'ASEAN', 'Big Shot', 15, 1500) 
    ON DUPLICATE KEY UPDATE num_responses = (num_responses + 15), 
    sat_total = (sat_total + 1500), 
    specialty = CONCAT(specialty, 
    (IF(LOCATE('Computers,',specialty) > 0, '', 'Computers,')))