我是靠谱客的博主 伶俐茉莉,最近开发中收集的这篇文章主要介绍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

最后

以上就是伶俐茉莉为你收集整理的mysql if update_使用IF条件的MySQL更新的全部内容,希望文章能够帮你解决mysql if update_使用IF条件的MySQL更新所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(52)

评论列表共有 0 条评论

立即
投稿
返回
顶部