我有一个名为transactions
的表,有5个字段。我正在针对update
= name
并按jane
递增transaction
的列运行1
查询。如何在date_created – tran_date = 1 month
时使用if语句并将值设置为transaction = 0
,tran_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);
答案 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
语句的开销更大。