SQL server查询,奇怪的行为

SQL server查询,奇怪的行为,sql,sql-server,Sql,Sql Server,我有以下SQL查询: SELECT UserChiamante.UserId as UserId FROM Something WHERE Something AND UserChiamante.UserId = ChiamanteInterno.UtenteId 结果是这样的: _________________ | UserId | |_______________| | 1008 | |-----------

我有以下SQL查询:

SELECT  UserChiamante.UserId as UserId

FROM    Something

WHERE   Something AND
        UserChiamante.UserId = ChiamanteInterno.UtenteId 
结果是这样的:

_________________
|     UserId    |       
|_______________|
|     1008      |
|---------------|
|     1022      |
|---------------|
|     1032      |
|_______________|
没关系。 但如果我在中更改查询:

SELECT  UserChiamante.UserId as UserId

FROM    Something

WHERE   Something AND
        UserChiamante.UserId != ChiamanteInterno.UtenteId 
我期待一个不同的结果,但我得到了一些奇怪的结果,如:

_________________
|     UserId    |       
|_______________|
|     1008      |
|---------------|
|     1022      |
|---------------|
|     1032      |
|---------------|
|     1258      |
ID1258没问题,因为我在ChiamateInterno表中没有这个ID,但其他3个ID在ChiamateInterno表中(obv,可以从查询的第一个版本中看到)

Obv“utinteid”是“UserId”的外键


那么为什么选择此记录呢???

您应该真正显示更多的查询和示例结果

但是,我很确定问题在于你没有完全理解连接。毕竟,您甚至没有在
on
子句中使用正确的
join
语法。一个好的猜测是您希望排除第二个表中的内容

对于您的查询,请执行以下操作:

where UserChiamante.UserId not in (select UtenteId from ChiamanteInterno)

当然,确切的语法和结构可能会有所不同,这取决于查询的其余部分。

我假设第一个查询类似于:

SELECT  UserChiamante.UserId as UserId
FROM    UserChiamante, ChiamanteInterno
WHERE   UserChiamante.UserId = ChiamanteInterno.UtenteId;
首先,将其重写为显式的
JOIN

SELECT  UserChiamante.UserId as UserId
FROM    UserChiamante JOIN ChiamanteInterno ON
        UserChiamante.UserId = ChiamanteInterno.UtenteId;
那么我假设您在第二个查询中需要一个外部联接。因此,请尝试:

SELECT  UserChiamante.UserId as UserId
FROM    UserChiamante LEFT JOIN ChiamanteInterno ON
        UserChiamante.UserId = ChiamanteInterno.UtenteId
WHERE   UserChiamante.UserId IS NULL;

或者可能相反。

您的查询在语法上不正确。为了更好地理解问题,您必须提供完整的查询。请您展开
某物
某物
?您正在实现一个联接,并且可能尝试进行一个外部联接,但是您得到的几乎是笛卡尔积,因为每一行都将被另一个表中的几乎每一行联接。