我有以下查询:
select vw.CONFERENCEID, alert.ALERTID, del.CHANNELID, del.DOCUMENTTEMPLATEID,
vw.starttime, vw.CONFERENCEID, alert.ALERTATTRIBUTEID,
alert.ALERTCATEGORYID, alert.ATTACHMENT, alert.ATTACHMENTLOCATION,
alert.ATTACHMENTNAME
from TBLMCONFERENCE vw,
TBLMSYSTEMALERTS alert,
TBLMALERTDELIVERYREL del,
tblmstandardmaster sm
WHERE alert.Alertid = del.alertid
and sm.masterid = del.CHANNELID
and alert.SYSTEMGENERATED = 'N'
and alert.alertid not in (
select sent.ALERTID
from TBLMSENTALERTHISTORY sent
where sent.REFACCOUNTID = vw.conferenceid
and sent.ALERTID = alert.ALERTID
and sent.CHANNELID = del.CHANNELID
and sent.RESETFLAG = 'N')
即使TBLMSENTALERTHISTORY
表中存在匹配记录,我也会收到记录。
此查询有什么问题吗?
答案 0 :(得分:1)
我不确定你为什么要获取数据,也许你可以用一些表和插入来构建一个小例子。
但是,我可以指出您对NOT IN
运算符的使用不是标准的:在大多数情况下,您不应该使用IN
和NOT IN
运算符将子查询加入主查询(这是多余的)。相反,你会写:
SELECT *
FROM TBLMCONFERENCE vw,
TBLMSYSTEMALERTS alert,
TBLMALERTDELIVERYREL del,
tblmstandardmaster sm
WHERE alert.Alertid = del.alertid
AND sm.masterid = del.CHANNELID
AND alert.SYSTEMGENERATED = 'N'
AND (alert.alertid, del.CHANNELID, vw.conferenceid)
NOT IN (SELECT sent.ALERTID, sent.CHANNELID, sent.conferenceid
FROM TBLMSENTALERTHISTORY sent
WHERE sent.RESETFLAG = 'N')
在您的情况下,您可以直接使用子查询NOT EXISTS
:
SELECT *
FROM TBLMCONFERENCE vw,
TBLMSYSTEMALERTS alert,
TBLMALERTDELIVERYREL del,
tblmstandardmaster sm
WHERE alert.Alertid = del.alertid
AND sm.masterid = del.CHANNELID
AND alert.SYSTEMGENERATED = 'N'
AND NOT EXISTS
(SELECT sent.ALERTID
FROM TBLMSENTALERTHISTORY sent
WHERE sent.REFACCOUNTID = vw.conferenceid
AND sent.ALERTID = alert.ALERTID
AND sent.CHANNELID = del.CHANNELID
AND sent.RESETFLAG = 'N')
请注意,通常NOT IN
和NOT EXISTS
不相同,because of NULLs。