开发者

MySQL Select statement Where table1.id != table2.id

I have a table of data which has posts, then I have a separate table of data which h开发者_如何学编程as 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


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.


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.


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜