如何使用单个语句更新多个列

时间:2016-09-25 19:24:50

标签: sqlite

我正在根据第Country1列中逗号分隔的国家/地区字符串更新一系列列Country2Country 9 ... Country,并且流程为花了很长时间:

cur.execute("UPDATE t SET Country1 = returnCountryName(Country,0) WHERE Country IS NOT NULL;")
cur.execute("UPDATE t SET Country2 = returnCountryName(Country,1) WHERE Country IS NOT NULL;")
cur.execute("UPDATE t SET Country3 = returnCountryName(Country,2) WHERE Country IS NOT NULL;")
cur.execute("UPDATE t SET Country4 = returnCountryName(Country,3) WHERE Country IS NOT NULL;")
cur.execute("UPDATE t SET Country5 = returnCountryName(Country,4) WHERE Country IS NOT NULL;")
cur.execute("UPDATE t SET Country6 = returnCountryName(Country,5) WHERE Country IS NOT NULL;")
cur.execute("UPDATE t SET Country7 = returnCountryName(Country,6) WHERE Country IS NOT NULL;")
cur.execute("UPDATE t SET Country8 = returnCountryName(Country,7) WHERE Country IS NOT NULL;")
cur.execute("UPDATE t SET Country9 = returnCountryName(Country,8) WHERE Country IS NOT NULL;")
cur.execute("UPDATE t SET Country10 = returnCountryName(Country,9) WHERE Country IS NOT NULL;")

使用一个语句会更快,怎么样?像......那样......

cur.execute("UPDATE t 
    SET Country1 = returnCountryName(Country,0) WHERE Country IS NOT NULL
    SET Country2 = returnCountryName(Country,1) WHERE Country IS NOT NULL
    SET Country3 = returnCountryName(Country,2) WHERE Country IS NOT NULL
    ...
    ;")

1 个答案:

答案 0 :(得分:0)

正确的方法就是这样:

UPDATE t 
SET Country1 = returnCountryName(Country,0),
    Country2 = returnCountryName(Country,1),
    Country3 = returnCountryName(Country,2),
    ...
    Country10 = returnCountryName(Country,9)
WHERE Country IS NOT NULL;

这也应该比执行多个查询更快,因为它将扫描表并仅重写行一次。