2017-08-01 85 views
1

迅速分離成字符串列表我有一個MySQL表看起來是這樣的:轉換逗號在MySQL

>> customer_table 

customerId | list1 | list2 | list3 
-------------------------------------------- 
    0  | 0,1,2,3 | 3,2,443,3| 3,55,3,4 
-------------------------------------------- 
    1  | 5,1,8,9 | 5,2,41,6 | 1,5,3,90 

列客戶ID是一個i​​nt主鍵。其餘的字段是逗號分隔的字符串列表(所以list1是'0,1,2,3'等)存儲在中文文本字段中。每個中文字段大約有500,000個字符(其中有近12萬個數字)非常大。

我想查詢此表,以便我可以快速將列表轉換爲數字,然後獲取解析列表的第i個元素並返回它們。我主要是一次查詢一行customer_table,但如果過程很快,有時可能會更多。僞代碼(寫得不好的)會是這個樣子

>> select csv_parsed(list1) # need to search a parsed version of the list 
from customer_table 
where customerId = 0 
and index = 0 or index = 1 or index = 4 # These are the ith elements of the parsed list 

應該返回沿着線的東西:

>> customerId | 0 | 1 | 4 
    ----------------------- 
     0  | 0 | 1 | 3 
+0

從技術上講,這不是一個真正的mysql表 - 但請參閱https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems -to-a-very-simple-sql-query – Strawberry

+0

謝謝草莓,我不確定你發佈的文章和我的問題之間有什麼關係?我在問題中繪製的示例表正是我們的數據庫看起來像在mysql中實現的那樣 – kPow989

+0

那麼,當您找出連接時,請告訴我們。 – Strawberry

回答

1

SQL不支持具有動態選擇列表中的查詢。選擇列表中的列在您準備查詢時已修復,執行過程中發現的數據無法擴展或重命名選擇列表中的列。

您可能會喜歡看SUBSTRING_INDEX()。這是MySQL中的一個內置函數,它可以挑選出您想要的字符分隔的子字符串。

select customerId, 
    substring_index(substring_index(list1, ',', 1), ',', -1) AS 0, 
    substring_index(substring_index(list1, ',', 2), ',', -1) AS 1, 
    substring_index(substring_index(list1, ',', 4), ',', -1) AS 4, 
from customer_table 
where customerId = 0 

下一次,如果要使用列表中的單個元素,請不要將數據存儲在以逗號分隔的字符串中。