如果声明:日期字段为1个月或更早

时间:2015-02-01 14:44:28

标签: mysql sql

我有一个名为transactions的表,有5个字段。我正在针对update = name并按jane递增transaction的列运行1查询。如何在date_created – tran_date = 1 month时使用if语句并将值设置为transaction = 0tran_date = 0000-00-00,并将date_created更改为新的当前日期。

查询

UPDATE transactions SET transactions = transactions + 1, tran_date = CURDATE()  WHERE name = 'jim'

创建表格并设置值:

CREATE TABLE transactions
(
  id int auto_increment primary key,
  date_created DATE,
  name varchar(20),
  transactions int(6), 
  tran_date DATE
);

INSERT INTO transactions
(date_created, name, transactions, tran_date)
VALUES
(NOW(), 'jim', 0, 0000-00-00),
(NOW(), 'jane', 0, 0000-00-00);

1 个答案:

答案 0 :(得分:1)

一种方法是使用case语句:

UPDATE transactions
    SET transactions = (case when tran_date >= date_sub(CURDATE(), interval 1 month)
                             then transactions + 1 else 0
                        end),
        tran_date = (case when tran_date >= date_sub(CURDATE(), interval 1 month)
                          then CURDATE() 
                          else '0000-00-00'
                     end),
        date_created = (case when tran_date >= date_sub(CURDATE(), interval 1 month)
                             then date_created 
                             else CURDATE()
                         end)
    WHERE name = 'jim';

另一种方法是使用两个单独的update s来执行此操作:

UPDATE transactions
    SET transactions = transactions + 1 
    WHERE name = 'jim' and tran_date >= date_sub(CURDATE(), interval 1 month)

UPDATE transactions
    SET transactions = 0,
        tran_date = '0000-00-00',
        date_created = CURDATE()
    WHERE name = 'jim' and tran_date < date_sub(CURDATE(), interval 1 month)

我认为逻辑可能更清晰,但两个update语句的开销更大。