2014-12-04 59 views
0

我一直試圖做一些CSV文件中使用SQL合併在Python與SQL查詢爲以下幾點:SQL查詢給人OperationalError:近「WITH」:語法錯誤

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:接近「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

回答

-1

添加 ';' With as

;WITH 
MATCHES AS(... 
+0

謝謝你的迴應。但錯誤仍然存​​在。 – abn 2014-12-04 07:31:23

+0

它是mysql/T-sql還是什麼? – Deepshikha 2014-12-04 07:35:36

0

自SQLite 3.8.3開始支持WITH子句。 隨Python 2.7發佈的版本要舊得多。

更新到最新的Python,或使用其他數據庫驅動程序(如apsw),或者,如果Python與動態庫一起編譯,請嘗試替換SQLite庫文件。

+0

+1:顛覆sqlite到3.21.0爲我解決了這個問題。 -1:sqlite不是Python的一部分。請參閱https://stackoverflow.com/a/1553190/2166224。 – kidmose 2018-01-12 17:05:54

相關問題