我希望使用Python将嵌套列表插入mysql表。我想为新的ID值插入新行,并为那些具有现有ID值的列更新某些列。但是,对于这些嵌套列表之一(Fruits,s [2]),如果这些记录为空,我只想更新mysql表中的这些行!我意识到我提出的查询仅适用于新的插入ID号,而不涉及更新现有行。那是我需要帮助的地方!
s = [[1, 20, 21],[1999, 1998, 1990], ['Apple', 'Pear', 'Bannana']
id = s[0]
yearborn = s[1]
favfruit = s[2]
query = '''INSERT INTO table (PersonID, Year, Fruit)
VALUES (%s, %s, %s)'''
cursor.executemany(query, s)
我想为新的ID值插入新行,并为那些具有现有ID值的列更新某些列。
在MySQL中,您可以使用insert ... on duplicate key
syntax,以及某些条件逻辑,仅将insert ... on duplicate key
列update
最初是fruit
:
null
为此,您需要在列insert into table (personid, year, fruit)
values (%s, %s, %s)
on duplicate key update
year = values(year),
fruit = case when fruit is null then values(fruit) else fruit end;
上使用唯一(或主键)约束。