如何为更新创建动态值?

时间:2018-05-08 10:55:57

标签: mysql sql

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

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

现在我需要让它更先进。目前它总是增加+ 1。我想加入users表并检查这些:

  1. 如果role_id == 1+ 5
  2. 如果reputation > 5000+ 5
  3. 我该怎么做?

    这就是我所做的。我想用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
    

2 个答案:

答案 0 :(得分:1)

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 

答案 1 :(得分:0)

您可以使用单个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);