sql 不存在查询
Posted
技术标签:
【中文标题】sql 不存在查询【英文标题】:sql Not exists query 【发布时间】:2011-12-17 07:19:49 【问题描述】:我有以下 sql 查询
declare @temp table(RevisionStatus varchar(100),DocTypeID varchar(50))
insert into @temp(RevisionStatus,DocTypeID)
select distinct md.RevisionStatus,dt.DocumentTypeID
from MissingDesignData md inner join tblDocumentType dt on md.[Doc Type]=dt.DocumentType inner join tblRevisionStatus rv on md.RevisionStatus=md.RevisionStatus
select distinct tm.RevisionStatus,tm.DocTypeID as 'DocType'
from @temp tm
rv.RevisionStatus=tm.RevisionStatus and rv.DocType=tm.DocTypeID
where not exists (select distinct rss.RevisionStatus,rss.DocType from tblRevisionStatus rss)
我需要返回tblRevisionStatus表中不存在但@temp表中存在的记录。目前它返回空数据集
当我选择@temp 数据时,如下所示
RevisionStatus DocType
PEN - Pending 14
PEN - Pending 16
PEN - Pending 2
PEN - Pending 3
PEN - Pending 30
PEN - Pending 34
PEN - Pending 5
PEN - Pending 55
tblRevisionStatus 数据集返回为
RevisionStatus DocType
IFC - Issued For Construction 4
RFD - Revised As Denoted 4
IFU - Issued For Use 4
AB - As Built NULL
C1 - Proceed, No Exception Taken 2
PEN - Pending 1
PEN - Pending 2
HLD - HOLD (Implementation Study ONLY) 1
当我运行上面给定的 sql 查询时,它什么也不返回。但只有
PEN - Pending 2
记录存在于 tblRevisionStatus 表中,为什么查询不返回其他记录。我在这里遗漏了什么吗?
【问题讨论】:
【参考方案1】:如果您想要在@Temp
中但不在tblRevisionStatus
中的行列表,您可以使用EXCEPT 语句轻松完成此操作
select RevisionStatus, DocType
from @Temp
except
select RevisionStatus, DocType
from tblRevisionStatus
【讨论】:
【参考方案2】:实际方法是针对此类需求使用主键,但您可以尝试在将数据传输到临时表后按照代码选择结果
SELECT RevisionStatus,DocTypeID as 'DocType'
from @temp where RevisionStatus not in(select distinct RevisionStatus From tblRevisionStatus) and DocTypeID not in (select distinct DocTypeID From tblRevisionStatus)
我仍然强调在所有表中使用主键
【讨论】:
ohh.i 更正了它,但仍然是相同的结果。最终结果集中没有数据【参考方案3】:我建议您不要使用 IN 和 DISTICTS。在大多数情况下,这些对性能不利。所以我的建议是这样的:
SELECT
tbl.RevisionStatus,
tbl.DocTypeID as 'DocType'
FROM
@temp AS tbl
WHERE NOT EXISTS
(
SELECT
NULL
FROM
tblRevisionStatus
WHERE
tblRevisionStatus.RevisionStatus=tbl.RevisionStatus
)
AND NOT EXISTS
(
SELECT
NULL
FROM
tblRevisionStatus
WHERE
tblRevisionStatus.DocTypeID=tbl.DocTypeID
)
【讨论】:
以上是关于sql 不存在查询的主要内容,如果未能解决你的问题,请参考以下文章