[英]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 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.
删除帖子后会发生的情况是,它的ID被添加到已删除的表中而不是删除帖子条目。
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 什么是从posts表中选择所有帖子而不选择在已删除表中具有其ID的那些帖子的干净有效方式
Would it not be easier to add an extra column to your posts table and store and boolean value of deleted? 在posts表中添加一个额外的列并删除存储和布尔值会不会更容易? Or use an integer field (to represent user id) if you want to store who deleted it, 0 = not deleted.
或者如果要存储删除它的人,则使用整数字段(表示用户ID),0 =未删除。
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). 如果你不能改变你的表,你可以做一个
Left Join
(在可能的情况下将加入你的deleted_table
),然后检查id
为Null
(意味着没有找到任何行)。
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. 确保在两个
id
-columns上都有索引以获得最佳性能。
If you have a good reason not to use a boolean flag as bigstylee suggests, you can use an EXISTS subquery: 如果你有充分的理由不像bigstylee建议的那样使用布尔标志,你可以使用EXISTS子查询:
SELECT * FROM table1
WHERE NOT EXISTS
(SELECT * FROM table2 WHERE table1.id=table2.id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.