SQLite 查询中的 CASE 语句

发布于 2024-10-16 23:56:54 字数 556 浏览 6 评论 0原文

为什么这个查询不起作用? :( 我尝试替换嵌套 IF 语句“...SET lkey = IF(lkey >= 11, lkey - 5, IF(lkey > 5, lkey + 2,lkey))”

UPDATE pages
SET lkey = CASE lkey WHEN lkey >= 11 THEN
        lkey - 5
    ELSE
        CASE lkey WHEN lkey > 5 THEN
            lkey + 2
        ELSE
            lkey
        END
    END,
    rkey = CASE lkey WHEN lkey >= 11 THEN
        rkey - 5
    ELSE
        CASE rkey WHEN rkey < 11 THEN
            rkey + 2
        ELSE
            rkey
        END
    END
WHERE rkey > 5 AND
    lkey < 12;

Why this query doesn't work? :( I tried to replace nested IF statement "...SET lkey = IF(lkey >= 11, lkey - 5, IF(lkey > 5, lkey + 2,lkey))"

UPDATE pages
SET lkey = CASE lkey WHEN lkey >= 11 THEN
        lkey - 5
    ELSE
        CASE lkey WHEN lkey > 5 THEN
            lkey + 2
        ELSE
            lkey
        END
    END,
    rkey = CASE lkey WHEN lkey >= 11 THEN
        rkey - 5
    ELSE
        CASE rkey WHEN rkey < 11 THEN
            rkey + 2
        ELSE
            rkey
        END
    END
WHERE rkey > 5 AND
    lkey < 12;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

煮茶煮酒煮时光 2024-10-23 23:56:54

该子句(以及类似的子句)中的语法是错误的,

    CASE lkey WHEN lkey > 5 THEN
        lkey + 2
    ELSE
        lkey
    END

它是

    CASE WHEN [condition] THEN [expression] ELSE [expression] END

或者

    CASE [expression] WHEN [value] THEN [expression] ELSE [expression] END

因此在您的情况下它将显示为:

    CASE WHEN lkey > 5 THEN
        lkey + 2
    ELSE
        lkey
    END

查看文档(CASE表达式):

http://www.sqlite.org/lang_expr.html

The syntax is wrong in this clause (and similar ones)

    CASE lkey WHEN lkey > 5 THEN
        lkey + 2
    ELSE
        lkey
    END

It's either

    CASE WHEN [condition] THEN [expression] ELSE [expression] END

or

    CASE [expression] WHEN [value] THEN [expression] ELSE [expression] END

So in your case it would read:

    CASE WHEN lkey > 5 THEN
        lkey + 2
    ELSE
        lkey
    END

Check out the documentation (The CASE expression):

http://www.sqlite.org/lang_expr.html

紫竹語嫣☆ 2024-10-23 23:56:54

此外,您不必使用嵌套 CASE。您可以使用多个 WHEN-THEN 行,并且 ELSE 行也是可选的,尽管我推荐它

CASE 
   WHEN [condition.1] THEN [expression.1]
   WHEN [condition.2] THEN [expression.2]
   ...
   WHEN [condition.n] THEN [expression.n]
   ELSE [expression] 
END

Also, you do not have to use nested CASEs. You can use several WHEN-THEN lines and the ELSE line is also optional eventhough I recomend it

CASE 
   WHEN [condition.1] THEN [expression.1]
   WHEN [condition.2] THEN [expression.2]
   ...
   WHEN [condition.n] THEN [expression.n]
   ELSE [expression] 
END
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文