我有两张这样的桌子:
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
我该怎么做?
答案 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 JOINS
或NOT 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