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

Python 如何使用Sqlite将逗号分隔的值拆分为多行,python,sqlite,Python,Sqlite,我正在使用Python和SQLite在android中操作字符串。 我有一个SQLite表,如下所示: | ID | Country +----------------+------------- | 1 | USA, Germany, Mexico | 2 | Brazil, Canada | 3 | Peru 我想拆分Country列的逗号分隔值,并将它们插入另一个表count

我正在使用Python和SQLite在android中操作字符串。 我有一个
SQLite
表,如下所示:

| ID             | Country     
+----------------+-------------
| 1              | USA, Germany, Mexico 
| 2              | Brazil, Canada
| 3              | Peru
我想拆分Country列的逗号分隔值,并将它们插入另一个表countries中,以便countries表如下所示

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

如何从一个表中的Country列中拆分值并将其插入另一个表的Country列中?

SQLite中没有
split
函数
当然有
子字符串
函数,但它不适合您的需要,因为每行可以包含多个逗号
如果您是SQLite方面的专家,我想您可以使用
substring
创建一个递归语句来拆分每一行
如果不使用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()
在使用sqlite db之后,另一个项目;:)

您可以使用递归提取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!='';