我无法将专为 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 中运行?
最佳答案
正如您所指出的,您可以使用 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 可以直接计算 bool 值,您可以稍微缩减此查询:
SELECT CASE WHEN sendonly THEN 'REJECT' ELSE 'OK' END AS access
FROM accounts
WHERE username = '%u' AND domain = '%d' AND enabled
LIMIT 1;
关于mysql - Postgres 中的 IF-ELSE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37778575/