Convert IF SQL from MySQL to PostgreSQL

I am converting a PHP script since the DB has been switched from MySQL to PostgreSQL.

I know that PG does not have an IF function, but has a CASE function. What is the best way to convert this MySQL statement?

  SELECT albums.id, 
         albums.albumname, 
         sum(if(((albums.id=allalbums.albumid) and 
             (allalbums.photoid=$photoid)),1,0)) as inalbum 
    FROM albums, allalbums 
GROUP BY albums.id 
ORDER BY albums.createdate desc
+3
source share
1 answer

Something like this should work:

select 
  albums.id, 
  albums.albumname, 
  sum(
   case when ((albums.id=allalbums.albumid) and (allalbums.photoid=$photoid)) then 1
     else 0
   end
  ) as inalbum 
from albums,allalbums 
group by albums.id 
order by albums.createdate desc
+4
source

Source: https://habr.com/ru/post/1735821/


All Articles