簡體   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