繁体   English   中英

仅当来自组的最新记录不同时才插入表中

[英]Insert into table only if most recent record from group is different

我有一个包含以下列的 MySQL 表:

score_id (int10, auto_increment, primary key); 
game_id (int10); 
away_team_score (int10); 
home_team_score (int10); 
date_time (datetime);

我正在抓取一个 web API(使用 python),我试图将一个数组写入该数据库。 但是,每次我阅读此 API 时,它都会提供所有事件的列表。 仅当每个 game_id 的 away_team_score 或 home_team_score 存在差异时,我才尝试写入此数据库。

我能够使用此示例中的查询( mySQL GROUP,最新)获取最新记录。 但是,我不确定如何检查我插入的值是否相同。

我不想使用更新,因为我想保留分数以供历史使用。 此外,如果 game_id 不存在,则应将其插入。

我目前拥有的 python 代码:

# Connecting to the mysql database
mydb = mysql.connector.connect(host="examplehost", user="exampleuser", passwd="examplepassword", database="exampledb")
mycursor = mydb.cursor()
# example scores array that I scraped
# It is in the format of game_id, away_team_score, home_team_score, date_time
scores = [[1, 0, 1, '2019-11-30 13:05:00'], [2, 1, 5, '2019-11-30 13:05:00'], [3, 4, 8, '2019-11-30 13:05:00'],
          [4, 6, 1, '2019-11-30 13:05:00'], [5, 0, 2, '2019-11-30 13:05:00']]

# Inserting into database
game_query = "INSERT INTO tbl_scores (game_id, away_team_score, home_team_score, date_time) VALUES (%s, %s, %s, %s)"

mycursor.executemany(game_query, scores)
mydb.commit()

mydb.close()

您需要使用 MySQL 中的 UPSERT 功能。 将插入查询更改为以下查询只会在有新游戏 ID 时插入,否则会更新分数:

INSERT INTO tbl_scores
    (game_id, score_id, away_team_score, home_team_score, date_time)
VALUES
    (game_id, score_id, away_team_score, home_team_score, date_time)
ON DUPLICATE KEY UPDATE
    game_id = game_id,
    away_team_score = away_team_score,
    home_team_score = home_team_score,
    date_time = date_time;

有关 upsert 的详细信息 - https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html

让我知道是否有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM