views:

20

answers:

2

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.

+2  A: 

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

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

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
Joe Stefanelli
the group by is for reasons that really are unrelated... I guess I should have just left it off for this example
tybro0103