我无法将为MySQL设计的SQL查询转换为Postgres语法。这是查询:
select if(sendonly = true, 'REJECT', 'OK') AS access from accounts where username = '%u' and domain = '%d' and enabled = true LIMIT 1;
这个漂亮的小功能“if()”在Postgres中不可用。我对CASE条款的第一次尝试失败了。需要修改哪些内容才能使此查询在Postgres中运行?
答案 0 :(得分:2)
如您所述,您可以使用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;