我一直在尝试使用Python中的SQL进行一些CSV文件合并,SQL查询如下:
WITH
MATCHES AS( -- get all matches
SELECT CSV2.*
, CSV1.ROW as ROW_1
, CSV1.C4 as C4_1
, CSV1.C5 as C5_1
FROM CSV2
LEFT JOIN CSV1
ON CSV1.C4 LIKE '%' || CSV2.C2 || '%'
),
EXACT AS( -- matches where CSV1.C4 = CSV1.C5
SELECT *
FROM MATCHES
WHERE C4_1 = C5_1
),
MIN_ROW AS( -- CSV1.ROW of first occurence for each CSV2.C1
SELECT C1
, min(ROW_1) as ROW_1
FROM MATCHES
WHERE C1 NOT IN (SELECT C1 FROM EXACT)
GROUP BY C1, C2, C3, C4, C5
)
-- use C4=C5 first
SELECT *
FROM EXACT
UNION
-- if match not in exact, use first occurence
SELECT MATCHES.*
FROM MIN_ROW
INNER JOIN MATCHES
ON MIN_ROW.C1 = MATCHES.C1
AND (MIN_ROW.ROW_1 = MATCHES.ROW_1 OR MIN_ROW.ROW_1 IS NULL)
ORDER BY C1
但是,我一直收到OperationalError:near" WITH":语法错误。我对SQL并不十分熟悉,并且之前没有尝试过在Python中使用它。可以做些什么来解决这个错误? Update1-第一对括号内的查询工作正常,没有"匹配为"部分。以下是示例csv文件: CSV1
data13 data23 d main_data1;main_data2 data13 data23
data12 data22 d main_data1;main_data2 data12 data22
data11 data21 d main_data1;main_data2 data11 data21
data3 data4 d main_data2;main_data4 data3 data4
data52 data62 d main_data3 data51 data62
data51 data61 d main_data3 main_data3 data61
data7 data8 d main_data4 data7 data8
CSV2
id1 main_data1 a1 a2 a3
id2 main_data2 b1 b2 b3
id3 main_data3 c1 c2 c3
id4 main_data4 d1 d2 d3
id5 main_data5 e1 e2 e3
和Python代码
import csv
import sqlite3
def createTable(cursor, rows, tablename):
tableCreated = False
for row in rows:
if not tableCreated:
sql = "CREATE TABLE %s(ROW INTEGER PRIMARY KEY, " + ", ".join(["c%d" % (i+1) for i in range(len(row))]) + ")"
cur.execute(sql % tablename)
tableCreated = True
sql = "INSERT INTO %s VALUES(NULL, " + ", ".join(["'" + c + "'" for c in row]) + ")"
cur.execute(sql % tablename)
conn.commit()
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
for filename, tablename in [(path_to_csv1, "CSV1"), (path_to_csv2, "CSV2")]:
with open(filename, "r") as f:
reader = csv.reader(f, delimiter=',')
rows = [row for row in reader]
createTable(cur, rows, tablename)
Update2-我使用Python 2.7
答案 0 :(得分:0)
自SQLite 3.8.3起支持WITH子句。 Python 2.7附带的版本要老得多。
更新到最新的Python,或使用其他数据库驱动程序,如apsw,或者,如果使用动态库编译Python,请尝试替换SQLite库文件。
答案 1 :(得分:-1)
添加';'在With
之前
;WITH
MATCHES AS( ...