mysql - SQL 如果不存在则插入新记录,否则更新现有记录
问题描述
我有 2 个表 Staging 和 Main Table 都有 SKU 和 Price 列。记录从那里插入到临时表中,具体取决于记录决定是插入新记录还是更新现有记录。我编写了多个查询,这些查询运行良好,但花费的时间比正常情况要长。我正在做的是:
Staging Table where data initially inserted into
+----------+--------------+-----------+-------+---------------------------------------------------------------------------------------------------------------------------+
| indexid | Persisted | sku | price | Logic |
+----------+--------------+-----------+-------+---------------------------------------------------------------------------------------------------------------------------+
| 1 | No | 4567456 | 10.99 | This row doesn't exists in main table so need to be inserted and update the persisted to NewProduct |
| 2 | No | 5463454 | 5.99 | This row exists and price matching then this simply need to be updated the persisted to PriceMatched |
| 3 | No | 5645654 | 4.75 | This row exists but price not matching, so new row to be inserted, updated existing record in both tables to PriceUpdated |
| 4 | PriceUpdated | 2222222 | 3.00 | |
| 5 | NewProduct | 5555555 | 4.00 | |
| 6 | PriceMatched | 7685765 | 5.00 | |
| 7 | PriceUpdated | 6574567 | 3.99 | |
+----------+--------------+-----------+-------+---------------------------------------------------------------------------------------------------------------------------+
+---------+--------------+---------+-------+
| indexid | status | sku | price |
+---------+--------------+---------+-------+
| 1 | Active | 5635674 | 10.99 |
| 2 | Active | 5463454 | 5.99 |
| 3 | Active | 5645654 | 2.75 |
| 4 | PriceUpdated | 2222222 | 3.00 |
| 5 | PriceUpdated | 5555555 | 4.00 |
| 6 | PriceMatched | 7685765 | 5.00 |
| 7 | PriceUpdated | 6574567 | 3.99 |
+---------+--------------+---------+-------+
如果 Product 在主表中不存在,则插入新记录并使用 persisted = 'NewProduct' 更新临时表
我正在从暂存表中选择所有记录,其中persisted = 'No' 然后插入新记录
UPDATE stagingTable SET persisted = 'NewProduct' WHERE indexid = '${indexID}';
Else 检查现有产品价格是否匹配,然后更新持久化 = 'PriceMatched'
UPDATE stagingTable SET persisted = 'PriceMatched' WHERE indexid = '${indexID}' ;
如果价格不匹配,则将新记录插入主表并更新现有记录状态 = 'PriceUpdated' 并且暂存表持久化 = 'PriceUpdated'
UPDATE mainTable SET productstatus = 'PriceUpdated' WHERE indexid = '${indexID}';
UPDATE stagingTable SET persisted = 'PriceUpdated' WHERE indexid = '${indexID}';
插入工作正常,但更新需要相当长的 10000 条记录,大约需要 15-20 分钟我通过批量插入和更新插入和更新。
这是我的逻辑
解决方案
推荐阅读
- python - PyTorch 设计:为什么 torch.distributions.multivariate_normal 在其类之外有方法?
- css - 即使使用不同的 id,也无法设置 2 个轮播
- ansible - ansible 2.7.10 中出现此错误的原因是什么 - “错误!剧本条目必须是有效的剧本或包含语句|”
- json - 逻辑应用:如何从 Http API cal 获取 display_value 响应
- google-cloud-platform - 在 Stackdriver 的错误报告中创建提醒政策
- javascript - 当我知道它是真的时,在 GTM 中将错误作为自定义 Javascript 返回
- excel - 如何在用户窗体中的特定单元格上设置我的输入数据?
- elixir - 由于 genserver 未启动,酿酒厂启动后挂钩失败
- sql-server - 如何使用以前行的平均值更新 SQL Server 中的行
- html - 调整窗口大小时如何修复图像?