使用每行的变量更新行中的列

问题描述 投票:0回答:1

我有一个数据库,并添加了一个附加列“团队”,所以它看起来像这样

date   |   forename   | surname   | team
-----------------------------------------
1/1/01 |   james      |  smith    | 
2/2/02 |   paul       |  jones    |
3/3/03 |   steven     |  bradley  |

我想向每个团队添加一个条目,使用团队列表中的随机包选择

import psycopg2
import random

dbconfig = {
    "dbname": "mydb",
    "host": "127.0.0.1",
    "user": "user",
    "password": "password",
    "port": 5432,
}

connection = psycopg2.connect(**dbconfig)
connection.autocommit = True

teams = ["liverpool", "chelsea", "arsenal"]
cursor = connection.cursor()

cursor.execute("select * from players")
players = cursor.fetchall()

for player in players:
    team = random.choice(teams)
    query = f""" update trades set team = '{team}' """

但是当我这样做时,它会更新每一行的团队,而不仅仅是当前的一行,所以我留下了

date   |   forename   | surname   | team
-----------------------------------------
1/1/01 |   james      |  smith    | chelsea
2/2/02 |   paul       |  jones    | chelsea
3/3/03 |   steven     |  bradley  | chelsea

我可以使用随机变量逐一或批量更新行吗?

python postgresql psycopg2
1个回答
1
投票

包含基于

WHERE
与特定
row
相匹配的
date, forename, & surname
子句。这样,每一行都将使用团队列表中的随机团队单独更新。

for player in players:
    team = random.choice(teams)
    query = f"UPDATE trades SET team = '{team}' WHERE date = '{player[0]}' AND forename = '{player[1]}' AND surname = '{player[2]}'"
    cursor.execute(query)
© www.soinside.com 2019 - 2024. All rights reserved.