mysql if update_使用IF条件的MySQL更新

bd96500e110b49cbb3cd949968f18be7.png

I'm not even sure if this is possible but I'm trying to do different UPDATE if a certain condition is met.

user [id, start_date(NOT NULL), end_date(NULL), reason(NULL), .....]

user_roles [id, role_id, user_id, start_date(NOT NULL), end_date(NULL)]

What I have right now is this but this only works if a role exists for the user and it's end_date is NULL:

UPDATE user p

JOIN user_roles ur ON p.id = ur.user_id

SET ur.end_date = NOW()

, p.end_date = NOW()

, p.reason = "Retired"

WHERE p.id = 5

AND ur.end_date IS NULL

I was thinking of doing something like this:

IF EXISTS (SELECT id FROM user_roles

WHERE user_id = 5 AND end_date IS NULL)

THEN

UPDATE user p

JOIN user_roles ur ON p.id = ur.user_id

SET ur.end_date = NOW()

, p.end_date = NOW()

, p.reason = "Retired"

WHERE p.id = 5 AND ur.end_date IS NULL

ELSE

UPDATE user

SET end_date = NOW()

, reason = "Retired"

WHERE id = 5

END IF

解决方案

Since the only difference is whether you are setting ur.end_Date to either the current Date or setting it to it's existing date could you not just use the following:

UPDATE user p

JOIN user_roles ur

ON p.id = ur.user_id

SET

ur.end_date = IF (ur.end_date IS NULL, NOW(), ur.end_date),

p.end_date = NOW(),

p.reason = "Retired"

WHERE p.id = 5

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值