简体   繁体   English

如何根据某些条件插入或更新?

[英]How to insert or update based on some condition?

Can someone please help me with this! 有人可以帮我这个忙! I have 2 tables: 我有2张桌子:

1.Existing pricing table with custom date-dependent pricing windows: 1.现有的定价表带有自定义的与日期相关的定价窗口:

  id | prod id |   start    |    stop    |   price  
-----+---------+------------+------------+-----------
   1 |   65210 | 2012-01-01 | 2013-01-01 |  5.00     
   2 |   54841 | 2012-02-05 | 2013-03-01 | 15.00     
   3 |   51518 | 2012-01-01 | 2013-01-01 |  5.00     
   4 |    8402 | 2012-01-01 | 2017-01-01 |  5.00     
   5 |    1520 | 2012-01-01 | 2050-01-01 | 12.00     
   6 |     959 | 2013-10-01 | 2018-01-01 |  5.00  

2."New" pricing data table (used to update table above by each unique prod id ): 2.“新”定价数据表(用于通过每个唯一的商品prod id来更新上面的表):

 prod id |   start    |    stop    |   price   
  -------+------------+------------+-----------
   65210 | 2013-01-01 | 2025-01-01 |  5.00     
   54841 | 2013-02-05 | 2017-03-01 | 15.00     
     959 | 2013-01-01 | 2017-01-01 |  5.00    

What's the best way to update the stop date in the table 1 with the stop date in table 2 assuming it's still "in window"? 什么是升级的最好办法stop在表1日起与stop表2日期假设它仍然是“窗口”? If the existing stop date is before the "new" start date, a new pricing record will be created with the new start and stop dates. 如果现有的stop日期早于“新” start日期,则将使用新的start日期和stop日期创建新的定价记录。

Thanks! 谢谢!

...To update the stop date in the table 1 with the stop date in table 2 assuming it's still "in window"... ......要更新stop日期表1与stop日期表2假设它仍然是“窗口” ......

UPDATE price p JOIN new_price n
    ON p.prod_id = n.prod_id
   AND n.start BETWEEN p.start AND p.stop
   SET p.stop = n.stop

To insert a new record "...if the existing stop date is before the new start date..." 插入新记录“ ...如果现有的stop日期早于新的start日期...”

INSERT INTO price (`prod_id`, `start`, `stop`, `price`)
SELECT n.prod_id, n.start, n.stop, n.price
  FROM new_price n JOIN price p
    ON n.prod_id = p.prod_id
   AND n.start > p.stop

Here is SQLFiddle demo 这是SQLFiddle演示

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

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