views:

143

answers:

3

I have a table of data which has posts, then I have a separate table of data which has deleted posts. What happens when a post is deleted is that it's ID get's added to the deleted table rather than removing the post entry.

What is a clean efficient way of selecting all the posts from the posts table without selecting the ones that have their ID in the deleted table

+2  A: 

Would it not be easier to add an extra column to your posts table and store and boolean value of deleted? Or use an integer field (to represent user id) if you want to store who deleted it, 0 = not deleted.

bigstylee
That would be easier, but this is for a 3rd party infrastructure that I haven't designed and I can't change the core structure for it.
Michael
A: 

If you have a good reason not to use a boolean flag as bigstylee suggests, you can use an EXISTS subquery:

SELECT * FROM table1 
  WHERE NOT EXISTS 
  (SELECT * FROM table2 WHERE table1.id=table2.id);
Tomas
this will work, but a simple left join would be much easier than doing a subselect.
oezi
I disagree. This seems much clearer and readable to me as it actually states what you are doing. In this simple example Mysql will optimize it the same..
Tomas
+1  A: 

If you can't change your tables, you can do a Left Join (which will join your deleted_table when possible) and then check for the id to be Null (means that no row has been found).

Select everything_you_need
From post_table p
Left Join delete_table d On ( d.id = p.id )
Where d.id Is Null;

Make sure to have indexes on both id-columns for best performance.

Peter Lang