我的桌子看起來像這樣
id effect1(int) effect2(int) effect3(int)
1 0 1 5
2 1 0 0
我有一個函式,它回傳代表 effect1、effect2、effect3 和“id”的 1to3 int 值
當我的函式回傳的“id”與我的資料集中的“id”匹配時,我試圖將每個效果的值增加 1,否則會創建新行并增加效果的值
例如
如果我的函式回傳 (1,3) 我的表將變為
id effect1(int) effect2(int) effect3(int)
1 0 1 6
2 1 0 0
如果我的函式回傳 (3,3) 我的表將變為
id effect1(int) effect2(int) effect3(int)
1 0 1 6
2 1 0 0
3 0 0 1
我使用python嘗試了以下代碼,但失敗了。有人可以幫我嗎
i = (1,3) # the returning value from my function
if i[1] == 1:
sql = "update test set effect1=effect1 1 WHERE id= ({})".format((str(i[0])))
db.execute_query(myDb, sql)
elif i[1] == 2:
sql = "update test set effect2=effect2 1 WHERE id= ({})".format((str(i[0])))
val = (i[0],)
db.execute_query(myDb, sql )
elif i[1] == 3:
sql = "update test set effect3=effect3 1 WHERE id= ({})".format((str(i[0])))
val = (i[0],)
db.execute_query(myDb, sql )
def execute_query(connection, query):
cursor = connection.cursor()
try:
cursor.execute(query)
connection.commit()
print("Query successful")
except Exception as err:
print(f"Error: '{err}'")
uj5u.com熱心網友回復:
假設這id是表的主鍵或者它被定義為唯一的,你可以使用 MySql 的INSERT ... ON DUPLICATE KEY UPDATE 陳述句,如下所示:
i = (1, 3)
sql = """
INSERT INTO test (id, effect1, effect2, effect3)
SELECT id, (n = 1), (n = 2), (n = 3) FROM (SELECT ? id, ? n) t
ON DUPLICATE KEY UPDATE effect1 = effect1 (n = 1),
effect2 = effect2 (n = 2),
effect3 = effect3 (n = 3);
"""
db.execute_query(myDb, sql, i)
def execute_query(connection, query, i):
cursor = connection.cursor()
try:
cursor.execute(query, i)
connection.commit()
print("Query successful")
except Exception as err:
print(f"Error: '{err}'")
查看有關如何在 MySql 中作業的演示。
uj5u.com熱心網友回復:
在您的實作中,您沒有檢查 是否id已經存在。
如您所述,我使用執行插入/更新的 SQL 陳述句更新了您的代碼-
- 如果
id存在則只需要增加特定效果 - 如果
id不存在,則id需要將新行添加/插入到test表中)
我還i用兩個命名的變數替換了變數(兩個元素的串列),id以effect_no提高代碼的可讀性。這些if else陳述句也不需要,因為effect_no可以使用/合并到 sql 陳述句本身。
以下是更新后的代碼:
id, effect_no = (1,3) # the returning value from your function
sql = f"""INSERT INTO test (id, effect1, effect2, effect3)
VALUES ({id}, 0, 0, 0)
ON DUPLICATE KEY UPDATE effect{effect_no} = effect{effect_no} 1"""
db.execute_query(myDb, sql)
def execute_query(connection, query):
cursor = connection.cursor()
try:
cursor.execute(query)
connection.commit()
print("Query successful")
except Exception as err:
print(f"Error: '{err}'")
另外,我在INSERT ... ON DUPLICATE KEY UPDATE這里找到了 SQL 陳述句https://chartio.com/resources/tutorials/how-to-insert-if-row-does-not-exist-upsert-in-mysql/#using-insert--on-重復鍵更新
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/441427.html
上一篇:從表中的許多列中過濾值
