如何在此查询中减号?

时间:2011-04-26 05:14:31

标签: sql sql-server sql-server-2005 tsql

当我进行减法时,我的查询出错了。我正在使用MS SQL。

SELECT PT.PcbId
  FROM dbo.DeviceTrace DT  
  JOIN dbo.PcbTrace  PT ON DT.CompId = '101125937' 
                       AND DT.DeviceID = PT.DeviceID

NOT IN (SELECT PB.PcbId
          FROM dbo.DeviceTrace DT 
          JOIN dbo.PcbTrace  PT ON DT.CompId = '101125937' 
                               AND DT.DeviceID = PT.DeviceID 
          JOIN dbo.PanelBlockTrace PB ON PB.PcbID = PT.PcbID)
你能纠正我吗?

6 个答案:

答案 0 :(得分:2)

我将您的查询重写为:

SELECT PT.PcbId
  FROM dbo.PcbTrace PT 
 WHERE EXISTS (SELECT NULL
                 FROM dbo.DeviceTrace DT 
                WHERE DT.DeviceID = PT.DeviceID 
                  AND DT.CompId = '101125937')
   AND NOT EXISTS (SELECT NULL
                     FROM dbo.PANELBLOCKTRACE pbt 
                    WHERE pbt.pcbid = PT.pcbid)

...因为您将第一次加入复制到NOT IN部分,但根据您提供的信息,PANELBLOCKTRACE和DEVICETRACE之间没有任何关系。

答案 1 :(得分:1)

当您说'不在'时,您必须指定字段名称 - 如下所示:


select PT.PcbId
from dbo.DeviceTrace DT  INNER Join dbo.PcbTrace  PT 
on DT.CompId = '101125937' and DT.DeviceID = PT.DeviceID

and [fieldName] not in 

(select PB.PcbId
from dbo.DeviceTrace DT  INNER Join dbo.PcbTrace  PT 
on DT.CompId = '101125937' and DT.DeviceID = PT.DeviceID 
INNER Join dbo.PanelBlockTrace PB
on
PB.PcbID = PT.PcbID)

或者如果你想在一个单独的where子句中使用它,那么你需要:


select PT.PcbId
from dbo.DeviceTrace DT  INNER Join dbo.PcbTrace  PT 
on DT.CompId = '101125937' and DT.DeviceID = PT.DeviceID

where [fieldName] not in

(select PB.PcbId
from dbo.DeviceTrace DT  INNER Join dbo.PcbTrace  PT 
on DT.CompId = '101125937' and DT.DeviceID = PT.DeviceID 
INNER Join dbo.PanelBlockTrace PB
on
PB.PcbID = PT.PcbID)

虽然,你应该使用'左连接'而不是'不在',这将更快..

答案 2 :(得分:1)

从您的查询中可以看出,您希望排除PanelBlockTrace符合您的CompID过滤条件的那些PcbID。

试试这个:

select PT.PcbId
from dbo.DeviceTrace DT  
INNER Join dbo.PcbTrace  PT on DT.CompId = '101125937' 
                            and DT.DeviceID = PT.DeviceID
LEFT JOIN dbo.PanelBlockTrace PB ON PB.PcbID = PT.PcbID    
WHERE PB.PcbID IS NULL

我希望这个解决方案超过WHERE PT.PcbId NOT IN,因为它需要一个匹配表,而不是NOT IN需要的那个。

答案 3 :(得分:1)

测试一下:

select PT.PcbId
from dbo.DeviceTrace DT  INNER Join dbo.PcbTrace  PT 
on DT.CompId = '101125937' and DT.DeviceID = PT.DeviceID
where PT.PcbId
not in 

(select PB.PcbId
from dbo.DeviceTrace DT  INNER Join dbo.PcbTrace  PT 
on DT.CompId = '101125937' and DT.DeviceID = PT.DeviceID 
INNER Join dbo.PanelBlockTrace PB
on
PB.PcbID = PT.PcbID)

答案 4 :(得分:0)

使用EXCEPT而不是NOT IN,因为:

SELECT query1

EXCEPT

SELECT query2

答案 5 :(得分:0)

你的查询似乎很好。

如果出现问题,请更具体。

此外,以下查询与您的相同:

SELECT PT.PcbId
FROM dbo.DeviceTrace DT  
  JOIN dbo.PcbTrace  PT ON DT.CompId = '101125937' 
                       AND DT.DeviceID = PT.DeviceID

EXCEPT

SELECT PcbId
FROM dbo.PanelBlockTrace

它具有更简单的结构,可以帮助您更轻松地发现问题。