tags:

views:

94

answers:

3

Let's say we have two tables here , posts and comments, the relations is one to many, there has a field call comment_date in the comments table.

Now I am struggle to get the expected results as follow:

All the posts have no comments after a certain date, can I done this by a SQL statement?

+1  A: 
SELECT  *
FROM    posts
WHERE   post_id NOT IN 
        (
        SELECT  comment_post
        FROM    comments
        WHERE   comment_date >= @deadline
        )
Quassnoi
Tested , worked as good as the first one , thanks. this is clever that don't need to specified the foreign key. as I use the post_id in the comments, so if replace the comment_post with post_id, it will be a perfect answer.
Shuoling Liu
NOT IN is actually optimized to NOT EXISTS in MySQL
Quassnoi
A: 
select *
from Posts P
left join Comments C
on C.PostId = P.PostId
and C.Date > SomeDate
where C.PostId is null

This will get everything from Posts, matched to any comments greater than a given date (Everything from the Left table matched with any which meet the conditions from teh Right table), then restrict to only those Posts which don't have any comments in the where.

Tetraneutron
+3  A: 
SELECT *
FROM posts p
WHERE NOT EXISTS(
    SELECT 1
    FROM comments c
    WHERE c.comment_date >= 'deadline'
    AND p.post_id = c.post_id
)
Milan Babuškov
Great, tested worked, learn keyword "NOT EXISTS", thanks.
Shuoling Liu
Thanks for swift answer.
Shuoling Liu