MySQL IF /查询转换为PostgreSQL

时间:2012-06-11 15:37:59

标签: mysql sql postgresql

我正在将一个站点从mysql迁移到PostgreSQL(到目前为止我真的很喜欢),但我对某个查询有疑问。请注意,这不是一个存储函数 - 这是一个在python脚本中手动传递的字符串(我知道这是一个可怕的做法,但它只适用于内部应用程序)。在mysql中,查询的结构如下:

SELECT 
  name,
  SUM(IF(is_correct, 1, 0)) AS correct,
  SUM(IF(is_correct, 0, 1)) AS wrong
FROM
  k_p AS p JOIN
  k_v AS v ON (variable_id=v.id)
WHERE
  content_type_id=%s %s %s
GROUP BY
  v.id
ORDER BY sort_order

is_correct只是一个布尔数据的列,可以是0或1.我意识到你不能像在mysql中那样在postgres中做直接的IF。该文档似乎表明,优选转换将使用case / when语句。我没有成功地尝试过。 SUM / IF语句是什么让我失望 - 其余的查询应该没问题。任何建议将不胜感激!

奖励问题:如果其中一个查询包括:

,您会怎么做?
 SUM(IF(ISNULL(is_correct), 0, 1)) AS wrong

2 个答案:

答案 0 :(得分:5)

您想要CASE构造:

SELECT 
  name,
  SUM(case when is_correct = 1 then 1 else 0 end) AS correct,
  SUM(case when is_correct = 1 then 0 else 1 end) AS wrong
FROM
  k_p AS p JOIN
  k_v AS v ON (variable_id=v.id)
WHERE
  content_type_id=%s %s %s
GROUP BY
  v.id
ORDER BY sort_order

答案 1 :(得分:1)

select name, correct, wrong
from (
    SELECT 
      id,
      name,
      count(nullif(is_correct, false)) AS correct,
      count(nullif(is_correct, true)) AS wrong
    FROM
      k_p AS p JOIN
      k_v AS v ON (variable_id=v.id)
    WHERE
      content_type_id=%s %s %s
    GROUP BY
      v.id, name
)
ORDER BY sort_order