Question

Because I use rails I've become rusty on sql since I rarely use it in rails. I have two related tables: comments 1:m comment_views

I want to find all comments where comment_views.viewed is false. Problem is, for some comments there is not a relating record in comment_views yet.

So far I have

select comments.id 
    from comments 
        left join comment_views 
            on comments.id = comment_views.comment_id 
    where comment_views.viewed != "t" 
    group by type_id, object_id 
    order by comments.created_at desc

But as stated, that doesn't return comments when there is no record in comment_views.

Was it helpful?

Solution

You can check for null if there is no record...

where comment_views.viewed != "t" or comments_views.viewed is null

OTHER TIPS

A couple of comments:

  1. As soon as you reference a column from your left-joined table (comment_views) in the where clause, you force the join to act as if it was an inner join. Put those conditions on the join instead.

  2. Not sure why you're doing the group by. I don't think it's needed.

So, the code should be:

select comments.id 
    from comments 
        left join comment_views 
            on comments.id = comment_views.comment_id 
                and comment_views.viewed != "t"
    order by comments.created_at desc
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top