I've been trying to convert a mySQL query in my Rails application to use Postgres Syntax and have been pouring over the Postgres documentation, specifically looking at the differences between conditionals. The query is:
Story.select('*', 'IF (views.id is null, 0, 1) as viewed')
.join('left join views on(
views.story_id = stories.id and views.user_id = ?
)', user.id)
.group(:id)
.order(viewed: :asc)
.order(id: :asc)
or as a pure query:
select stories.*,
IF (views.id is null, 0, 1) as viewed
from stories
left join views
on(views.story_id = stories.id and views.user_id = 1)
where 1
group by stories.id
order by viewed, stories.id
It seems postgres uses 'case' instead of IF, so I tired something like this:
Story.select('*', '(case when viewid is null then 0, 1 end) as viewed')
.join('left join views on(
views.story_id = stories.id and view.user_id = ?
)', user.id)
.group(:id)
.order(viewed: :asc)
.order(id: :asc)
but I get a
wrong number of arguments (2 for 0..1)
error...
I've tried several variations but with no luck. I'm planning to study SQL a bit more in the near future but in the mean time, I feel somewhat lost here.
Can anyone point out the finer details here of what the different syntax might be? Thanks!