【问题标题】:How do insert a time window of data into table that partially overlaps with existing rows with unique constraint如何将数据的时间窗口插入到与具有唯一约束的现有行部分重叠的表中
【发布时间】:2015-08-21 18:17:52
【问题描述】:

如何将数据的时间窗口插入到与具有唯一约束的现有行部分重叠的表中。

这是一个代码sn-p:

  # Create the insert strings
column_str = """data_vendor_id, symbol_id, price_date, created_date, 
             last_updated_date, open_price, high_price, low_price, 
             close_price, volume, adj_close_price"""
insert_str = ("%s, " * 11)[:-2]
final_str = "INSERT INTO daily_price (%s) VALUES (%s)" % \
    (column_str, insert_str)

当我现在调用它时,我得到了有意义的 IntegrityError。理想情况下,它将让新行插入并在冗余行上优雅地失败。不幸的是,我的 try/except 块不允许合法行并使整个查询失败:

   for i, t in enumerate(tickers):
    print(
        "Adding data for %s: %s out of %s" %
        (t[1], i+1, lentickers)
    )
    yf_data = price_retrieval.get_daily_historic_data_yahoo(t[1], start_date.timetuple())
    try:
        price_retrieval.insert_daily_data_into_db('1', t[0], yf_data)
    except IntegrityError:
        continue

是否有 python 或 mysql 解决方案可以使这种插入更容错?

【问题讨论】:

  • “不允许合法行”是什么意思?桌面上有哪些键,“部分重叠”是什么意思?
  • 唯一的约束是 pricedate 和ticker_id。部分重叠意味着我插入的某些行与前一行发生冲突,而某些行是新行“合法行”。帕特里克斯的回答奏效了。谢谢!

标签: python mysql


【解决方案1】:

您正在寻找INSERT IGNOREREPLACE,具体取决于您希望如何处理重复数据。

插入忽略
如果你想保留旧数据并丢弃新的重复数据,你想使用INSERT IGNORE。这会将唯一键违规变成警告,并且所有非违规行都将正常处理。如果没有 IGNORE 关键字,任何唯一违规都将中止整个 INSERT 批处理。

final_str = "INSERT IGNORE INTO daily_price (%s) VALUES (%s)" % \
    (column_str, insert_str)

Insert documentation

替换
如果你想用新的重复数据覆盖旧数据,你想使用REPLACE 语句而不是INSERTREPLACE 是 MySQL 对 SQL 标准的特定扩展。它会插入不存在的行,如果遇到重复行,会先删除旧行,再插入新行。

final_str = "REPLACE INTO daily_price (%s) VALUES (%s)" % \
    (column_str, insert_str)

Replace documentation

【讨论】:

    【解决方案2】:

    我的理解是price_retrieval.insert_daily_data_into_db 正在插入许多行,但是在第一个失败的行上中断?您需要用 try 包装单个记录插入,而不是包装它们的组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-30
      • 1970-01-01
      • 2016-10-28
      • 2018-08-22
      • 2011-07-09
      • 2013-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多