排除另一个表中存在的记录

时间:2017-09-03 07:54:26

标签: php mysqli

我有两张这样的桌子:

emails:
emailID int(10) auto_increment, memberID int(10), emailData text, and so on

members:
memberID int(10) auto_increment, user_name char(40), password char(50), and so on

我的疑问是:

select 
emails.emailID, emails.emailData, 
members.memberID, members.user_name 
from emails, members where
emails.memberID = members.memberID

现在我又添加了两个这样的表:

blocked:
id int(10) auto_increment, memberID int(10), blocked_memberID int(10)

markedAsRead:
id int(10) auto_increment, memberID int(10), emailID int(10)

我想修改原始查询,以便排除memberID中的blocked.blocked_memberID,并排除emailID

中的markedAsRead.emailID

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以使用NOT EXISTS

SELECT ....
FROM   .... 
WHERE  ..... // Replace the dots with Your Query
  AND NOT EXISTS(SELECT 1 FROM blocked
                 WHERE emails.memberID = blocked.memberID)
  AND NOT EXISTS(SELECT 1 FROM markedAsRead
                 WHERE emails.emailID = markedAsRead.emailID)

您还可以查找LEFT JOINSNOT IN以排除特定表格中不存在的记录。

编辑:通常EXISTS()LEFTJOIN具有相似的效果,有时它甚至可以比连接效果更好。

LEFT JOIN闷闷不乐:

SELECT ...
FROM ...
LEFT JOIN blocked 
 ON(WHERE emails.memberID = blocked.memberID)
LEFT JOIN markedAsRead
 ON(emails.emailID = markedAsRead.emailID)
WHERE ...
 AND blocked.memberID IS NULL
 AND markedAsRead.emailID IS NULL