请考虑此查询:
SELECT tesd.State_Code,
tesd.City_Code,
tesd.Row_ID,
tesd.Qsno,
tesd.Total_Period,
tesd.Current_Period,
tesd.Week,
tesd.Block_No,
tesd.Family_ID,
tesd.Line_ID,
tesd.Page_ID
INTO #tmp
FROM Specification_Master tesm
INNER JOIN Specification_Details tesd
ON tesd.Master_Id = tesm.Id
WHERE tesm.[Year] = 2000
AND tesm.[Month] = 10
AND tesd.City_Code IN ('001')
我从2个表中查询了一些数据并将它们插入到#tmp
中。然后我想从其他2个表中选择数据并检查其中一个表的值是否为#tmp
tbale:
SELECT *
FROM tbl_Details D
INNER JOIN tbl_Master tem
ON D.ID_Master = tem.Id
WHERE D.Period <= 5
AND EXISTS (
SELECT Row_ID
FROM #tmp tm
WHERE tm.Current_Period > 1
AND tm.State_Code = tem.State_Code
AND tm.City_Code = tem.City_Code
AND tm.Qsno = tem.Qsno
)
AND D.[Status] > 2
当我运行此查询时,我只有一行,但当我将EXISTS
更改为NOT EXISTS
时,我获得了更多行。我单独运行此查询:
SELECT Row_ID
FROM #tmp tm,tbl_Master tem
WHERE tm.Current_Period > 1
AND tm.Ostan_Code = tem.State_Code
AND tm.City_Code = tem.City_Code
AND tm.Porseshname_ID = tem.Qsno
并返回30行。为什么Exists
有这样的行为?
答案 0 :(得分:2)
Exists根据子查询的结果返回一个布尔值。重要的不是返回1行或30行。您要检索的行数基于select *语句,而不是Exists子句。