简体   繁体   中英

MySQL IF/query conversion to PostgreSQL

I'm migrating a site from mysql to PostgreSQL (which I really like so far) but I have a question regarding a certain query. Please note that this was not a stored function- this was a string that was passed in manually in a python script(I am aware this is a terrible practice, but it's for an internal app only). In mysql, the query was structured like so:

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 is just a column with boolean data, either a 0 or 1. I realize you can't do straight IFs in postgres as you would in mysql. The documentation seems to suggest that the preferably conversion would be to use a case/when statement. I have experimented with no success. The SUM/IF statements are what are throwing me off- the rest of the query should be fine. Any advice would be greatly appreciated!

BONUS Question: How would you do it if one of the queries included:

 SUM(IF(ISNULL(is_correct), 0, 1)) AS wrong

You want to you the CASE construct:

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
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM