sql - 对多个表使用 NOT IN

标签 sql tsql

如何简化多个“不在”查询?使用多个子查询是否有效:Not in (...) and Not in (..) and Not in (..)

我正在使用计数(抱歉忘记了)

 Select count (VisitorID)

 from Company

 where VisitorID not in (select VisitorID from UserLog where ActionID = 2 )

 and VisitorID not in (select VisitorID from Supplies where productID = 4)

最佳答案

Select count (VisitorID)

from Company C
where
NOT EXISTS (select * from UserLog U where ActionID = 2 AND C.VisitorID  = U.VisitorID)
AND
NOT EXISTS (select * from Supplies S where productID = 4 AND S.VisitorID  = U.VisitorID)

为什么不存在?
  • NOT IN:UserLog 或 Supplies 中的任何 NULL VisitorID 值表示不匹配
  • (LEFT JOIN):如果每个访问者 ID 有多个 UserLog 或 Supplies,则输出多个行。需要改变计划的 DISTINCT

  • 通常,NOT EXISTS 是唯一正确的选项

    关于sql - 对多个表使用 NOT IN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3805153/

    相关文章:

    c# - SQL : Update a row and returning a column value with 1 query

    MySQL:根据另一个列值在列中选择唯一值

    mysql - JRValidationException : Report design not valid

    sql-server - MDX 性能与 T-SQL

    sql - T-SQL : How to select one column or in alternative another one?

    sql-server - 创建具有不同列数的 SQL 表

    sql - 如何从 SQL Server DateTime 数据类型仅返回日期

    java - 使用存储过程优化查询

    mysql关系表在x数量的表之间分割id

    sql - 如何在 SQL Server 中将我的数据成百上千地分开?