如何为更新创建动态值?

xkrw2x1b  于 2021-06-25  发布在  Mysql
关注(0)|答案(2)|浏览(262)

以下是我当前的查询:(它是一个触发器)

UPDATE qanda SET closed = COALESCE(closed, 0) + 1 WHERE id = new.qanda_id

现在我需要让它更先进。目前它总是增加 + 1 . 我想加入 users 表格并检查:
如果 role_id == 1 那么 + 5 如果 reputation > 5000 那么 + 5 我该怎么做?
这就是我所做的。我想和你一起去 CASE WHEN (怎么做?)

BEGIN

SELECT reputation, role_id INTO @reputation , @role_id FROM users WHERE id = new.user_id;

IF (@reputation >= 5000 OR role_id == 1) THEN
    UPDATE qanda SET closed = COALESCE(closed, 0) + 5 WHERE id = new.qanda_id;
ELSE
    UPDATE qanda SET closed = COALESCE(closed, 0) + 1 WHERE id = new.qanda_id;
END IF

END
j8ag8udp

j8ag8udp1#

你可以用一个 UPDATE :

UPDATE qanda q JOIN
       users u
       ON q.id = new.qanda_id AND u.id = new.user_id
    SET q.closed = COALESCE(q.closed, 0) + 
                   (CASE WHEN u.reputation >= 5000 OR u.role_id = 1 THEN 5 ELSE 1 END);
mrphzbgm

mrphzbgm2#

update qanda q, users u 
set q.closed=COALESCE(q.closed, 0) + if((u.reputation >= 5000 OR u.role_id = 1),5,1)
where q.id = u.qanda_id

相关问题