简体   繁体   English

如何使用 Sqlite 将逗号分隔值拆分为多行

[英]How to split comma delimited values into multiple rows using Sqlite

I'm using Python and SQLite to manipulate a string in android. I have a SQLite Table that looks like this:我正在使用 Python 和SQLite来操作 android 中的字符串。我有一个SQLite表,如下所示:

| ID             | Country     
+----------------+-------------
| 1              | USA, Germany, Mexico 
| 2              | Brazil, Canada
| 3              | Peru

I would like to split the comma delimited values of Country column and insert them into another table countries so that Countries table looks like this我想拆分 Country 列的逗号分隔值并将它们插入另一个表 countries 以便 Countries 表看起来像这样

| ID             | Country     
+----------------+-------------
| 1              | USA
| 1              | Germany
| 1              | Mexico
| 2              | Brazil
| 2              | Canada
| 3              | Peru

How do I do split the values from Country column in one table and insert them into Country column of another table?如何拆分一个表中 Country 列的值并将它们插入另一个表的 Country 列?

There is no split function in SQLite. SQLite 中没有split功能。
There is of course the substring function but it's not suitable for your needs since every row could contain more than 1 commas.当然有substring函数,但它不适合您的需要,因为每一行都可能包含 1 个以上的逗号。
If you were an expert in SQLite I guess you could create a recursive statement using substring to split each row.如果您是 SQLite 的专家,我猜您可以创建一个使用substring拆分每一行的递归语句。
If you're not use Python to read the data, split each row and write it back to the db.如果您不使用 Python 读取数据,请将每一行拆分并将其写回数据库。

im solved im using python我用python解决了我

import sqlite3
db = sqlite3.connect(':memory:')
db = sqlite3.connect('mydb.db')
cursor = db.cursor()
cursor.execute("""Select * from Countries""")
all_data = cursor.fetchall()
cursor.execute("""CREATE TABLE IF NOT EXISTS Countriess
                    (ID TEXT,
                    Country TEXT)""")
for single_data in all_data:
    countriess  = single_data[1].split(",")
    for single_country in countriess :
        cursor.execute("INSERT INTO Countriess VALUES(:id,:name)", { "id": single_data[0], "name": single_country })
db.commit()

and after use sqlite db another project;并在使用 sqlite db 后另一个项目; :) :)

You can use a recursive common table expression to split the comma-delimited column by extracting substrings of the Country column recursively.您可以使用递归公用表表达式通过递归提取 Country 列的子字符串来拆分逗号分隔的列。

CREATE TABLE country_split AS
WITH RECURSIVE split(id, value, rest) AS (
   SELECT ID, '', Country||',' FROM country
   UNION ALL SELECT
   id,
   substr(rest, 0, instr(rest, ',')),
   substr(rest, instr(rest, ',')+1)
   FROM split WHERE rest!=''
)
SELECT id, value
FROM split
WHERE value!='';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM