简体   繁体   English

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

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

I have a MySQL table with the following columns:我有一个包含以下列的 MySQL 表:

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

I am scraping a web API (using python) which I am trying to write an array to this database.我正在抓取一个 web API(使用 python),我试图将一个数组写入该数据库。 However, each time I read this API it provides a list of all events.但是,每次我阅读此 API 时,它都会提供所有事件的列表。 I am trying to write to this database only when there is a difference in either the away_team_score or the home_team_score for each game_id.仅当每个 game_id 的 away_team_score 或 home_team_score 存在差异时,我才尝试写入此数据库。

I am able to get the most-recent records using the query from this example ( mySQL GROUP, most recent ).我能够使用此示例中的查询( mySQL GROUP,最新)获取最新记录。 However, I am unsure on how to check if the values that I am inserting are the same.但是,我不确定如何检查我插入的值是否相同。

I don't want to use update because I want to keep the scores for historical purposes.我不想使用更新,因为我想保留分数以供历史使用。 Also, if the game_id does not exist, it should insert it.此外,如果 game_id 不存在,则应将其插入。

My python code I currently have:我目前拥有的 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()

You need to make use of UPSERT functionality in MySQL.您需要使用 MySQL 中的 UPSERT 功能。 Changing your insert query to the following query will only insert when there is new game-id, else it will update the scores:将插入查询更改为以下查询只会在有新游戏 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;

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

Let me know if that helps.让我知道是否有帮助。

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

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