【问题标题】:sql insert if other row with same attribute and date > 1 day如果其他行具有相同的属性和日期 > 1 天,则 sql 插入
【发布时间】:2017-03-15 18:16:04
【问题描述】:

我想将行插入到具有日期和信息列的表中。如果已经有一行具有相同的信息值且日期与今天相差 >= 1 天,则不应发生插入。

假设当前日期:2017-01-03

id, info, date
1, a, 2017-01-01
2, b, 2017-01-02

要插入的新行:

info
c
a
b

预期操作:

c: gets inserted because no other row has the same info value
a: gets inserted because existing a has a date more than 1 day in the past
b: no insert because the time difference is not big enough

预期结果:

id, info, date
1, a, 2017-01-01
2, b, 2017-01-02
3, c, 2017-03-03
4, a, 2017-03-03

【问题讨论】:

  • 我认为您需要为此创建一个触发器。

标签: mysql sql


【解决方案1】:

对于该约束,您必须创建一个触发器以避免插入,这是一个未经测试的触发器示例,您可以实现您需要的任何逻辑:

CREATE OR REPLACE TRIGGER tg_triggername
  BEFORE INSERT OR UPDATE ON table_name
  FOR EACH ROW
BEGIN
  IF( your_logic )
  THEN
    RAISE_APPLICATION_ERROR( 
      -20002, 
      'can't in sert already a row with the same info value and a date that is >= 1 day difference to today' );
  END IF;
END;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-03
    • 2018-09-22
    • 1970-01-01
    • 2023-03-23
    • 2018-03-05
    • 1970-01-01
    • 1970-01-01
    • 2013-07-31
    相关资源
    最近更新 更多