【问题标题】:How to make a conditional IF THEN on this statement?如何在此语句上设置条件 IF THEN?
【发布时间】:2011-10-15 06:34:00
【问题描述】:

当用户提交支持时,这个 MySQL 会增加 5 个用户的声誉。

UPDATE  user_profiles
SET     reputation = reputation +5
WHERE   user_id = $question_author_id;

现在我要区分一下:

  • 如果赞成一个问题,则增量应为 5,
  • 如果投票是为了回答,则增量应为 10。

可以通过表 forum_qa 的字段 forum_qa_parent_id 中是否存在整数来识别答案。

所以我想出了这个,但它不起作用:

UPDATE       user_profiles
IF (SELECT   forum_qa_parent_id 
    FROM     forum_qa 
    WHERE    forum_qa_id = $question_id) IS NOT NULL 
    THEN SET reputation = reputation +10 
    WHERE    user_id = $question_author_id;
ELSE SET     reputation = reputation +5 
WHERE        user_id = $question_author_id;
END IF;

有人愿意告诉我如何完成这项工作吗?

【问题讨论】:

  • :) - 语法错误 - 很抱歉含糊不清...... - 但@derek 提供了一个很好的解决方案
  • 什么语法错误?

标签: mysql sql if-statement conditional


【解决方案1】:

如果您在查询中进行逻辑比较,则需要使用 CASE 语句。 http://dev.mysql.com/doc/refman/5.0/en/case-statement.html

UPDATE  user_profiles
SET     reputation = reputation + 
    case when (
        SELECT   forum_qa_parent_id 
        FROM     forum_qa 
        WHERE    forum_qa_id = $question_id) is not null then 10 else 5 end
WHERE   user_id = $question_author_id;

类似的东西 - 你可能需要稍微修改一下。

【讨论】:

  • 嗨@derek - 谢谢你的提示 - 在我做了一个小mod之后效果很好 - 我删除了exists并将is not null放在then 10...之前 - 我认为exists没有'不起作用,因为它检查的是一行而不是 NULL - 不确定是否是这种情况,但也许你可以更新答案?
  • EXISTS (SELECT ...) 非常常用。 @torr:你试过了吗?
  • 但你是对的,EXISTS 检查行。并且您想检查该字段是否有NULL
  • @ypercube:在这种情况下,该行始终存在。这是 OP 想要 CASE 的行的值。
猜你喜欢
  • 1970-01-01
  • 2013-01-14
  • 1970-01-01
  • 2012-07-16
  • 1970-01-01
  • 1970-01-01
  • 2019-04-21
  • 2011-05-10
  • 2023-04-05
相关资源
最近更新 更多