我有以下两个表
地块表
Blockid ParcelNo storPri ======= ======== ======= 52000105 3 State 52000105 4 Private 52000105 5 State
动作表
Blockid ParcelNo ActionTaken ======= ======== =========== 52000105 3 Received 52000105 3 Send to Computer 52000105 4 Received 52000105 5 Received
我想查找记录,Received但没有Send to Computer
Received
Send to Computer
这是我的查询
select l.blockid, l.parcelno from landparcels l left join actions ac on l.blockid = ac.blockid and l.parcelno = ac.parcelno where ac.actiontaken = 'Received' and ac.actiontaken <> 'Send to Computer' and ac.blockid = 52000105
结果是
Blockid ParcelNo ======= ======== 52000105 3 52000105 4 52000105 5
我要4号和5号包裹
请,在任何常用数据库产品中的AND运算符中都很难找到一个简单的错误。这里的问题不是数据库引擎没有产生正确的结果,而是您不了解AND运算符的作用。
看你的病情ac.actiontaken = 'Received' AND ac.actiontaken <> 'Send to Computer'。将会发生的是,引擎将检查输出中的每个可能的行,并确定它是否满足您指定的条件。那么,对于第一行,采取的动作是否为“已接收”,这是真的吗?是的。采取的措施不是“发送到计算机”是否也正确吗?当然。因此,该行符合条件。
ac.actiontaken = 'Received' AND ac.actiontaken <> 'Send to Computer'
实际上,采取行动为“已接收”的 任何 行均符合条件,因为根据定义, 对于该行 采取的行动也 并非 “发送至计算机” ,这也是事实。
有多种方法可以获取所需的答案。这是我的首选:
SELECT DISTINCT a.blockid, a.parcelno FROM actions a WHERE a.blockid = 52000105 AND a.actiontaken = 'Received' AND NOT EXISTS (SELECT * FROM actions a2 WHERE a2.blockid = a.blockid AND a2.parcelNo = a.parcelNo AND a2.actiontaken = 'Send to Computer')