【问题标题】:IF-ELSE in PostgresPostgres 中的 IF-ELSE
【发布时间】:2016-06-12 20:05:37
【问题描述】:

我未能将专为 MySQL 设计的 SQL 查询转换为 Postgres 语法。这是查询:

select if(sendonly = true, 'REJECT', 'OK') AS access from accounts where username = '%u' and domain = '%d' and enabled = true LIMIT 1;

Postgres 没有这个不错的小函数“if()”。我对某些 CASE 子句的第一次尝试失败了。需要修改哪些内容才能在 Postgres 中运行此查询?

【问题讨论】:

标签: mysql sql postgresql if-statement select


【解决方案1】:

如您所述,您可以使用 case 表达式:

SELECT CASE WHEN sendonly = true THEN 'REJECT' ELSE 'OK' END AS access
FROM   accounts
WHERE  username = '%u' AND domain = '%d' AND enabled = true
LIMIT  1;

或者,由于 Postgres 可以直接评估布尔值,您可以稍微精简一下这个查询:

SELECT CASE WHEN sendonly THEN 'REJECT' ELSE 'OK' END AS access
FROM   accounts
WHERE  username = '%u' AND domain = '%d' AND enabled
LIMIT  1;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多