views:

55

answers:

1

I'm converting a PHP script as DB has been switched from MySQL to PostgreSQL.

I know PG doesn't have the IF function but does have the 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
+1  A: 

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
Simon
@Simon: Good solution. I believe PostgreSQL requires all non-aggregate columns to be specified in the GROUP BY clause; whereas MySQL I believe does not (!?).
Adam Bernier
IF is not part of the SQL standards, that's why PostgreSQL doesn't have IF. The complete GROUP BY is also SQL standard, that's why you have to use a complete GROUP BY. Same in other databases, MySQL is the exception.
Frank Heikens