比较COUNT与INTERSECT

时间:2018-11-22 12:18:40

标签: sql sql-server intersect

我正在尝试在SQL中复制.NET的All运算符,但在使用sytax时遇到了麻烦。我有一个查询:

查询1

SELECT ExamId FROM UserExam where UserId = @UserId 

查询2

SELECT ExamId FROM Paper u2 JOIN UserPaper uu2 ON uu2.PaperId = u2.Id
WHERE uu2.UserId = u.id

我想检查查询1中是否存在查询2中的所有元素。这就是我所拥有的:

... AND
(SELECT COUNT(*) FROM
    (SELECT ExamId FROM UserExam where UserId = @UserId 
    INTERSECT
    SELECT ExamId FROM Paper u2 JOIN UserPaper uu2 ON uu2.PaperId = u2.Id
    WHERE uu2.UserId = u.id)
    I = (SELECT COUNT(*) c FROM UserExam where UserId = @UserId)
)

在最后一行的等号后面有一个语法错误,我不知道如何解决。是否有一个简单的解决方法,或者有更好的方法呢?

2 个答案:

答案 0 :(得分:0)

在评论之后,您只是不给子查询的 结果 加上别名。

您正在生成标量值,而不是集合。标量不需要别名,只需要设置即可。

但是您确实需要在生成标量值的子查询周围包裹(),然后再对其进行操作。

 SELECT 1  =  SELECT 2   -- syntax error
(SELECT 1) = (SELECT 2)  -- good syntax, evaluates to FALSE

所以...

(
  SELECT
    COUNT(*)
  FROM
  (
    SELECT ExamId FROM UserExam where UserId = @UserId 
    INTERSECT
    SELECT ExamId FROM Paper u2 JOIN UserPaper uu2 ON uu2.PaperId = u2.Id
      WHERE uu2.UserId = u.id
  )
    AS alias_for_the_intersection
)
=
(
  SELECT COUNT(*) c FROM UserExam where UserId = @UserId
)

答案 1 :(得分:0)

您的分组刚刚被松散。您需要在)别名后面添加I,然后在末尾添加一个。

就目前而言,它是将第一部分中的FROM子句与第二个查询进行比较,而不是将两个计数进行比较。

当前:

(SELECT COUNT(*) FROM
    (SELECT ExamId FROM UserExam where UserId = @UserId 
    INTERSECT
    SELECT ExamId FROM Paper u2 JOIN UserPaper uu2 ON uu2.PaperId = u2.Id
    WHERE uu2.UserId = u.id)
    I = (SELECT COUNT(*) c FROM UserExam where UserId = @UserId)
)

应该是:

(SELECT COUNT(*) FROM
    (SELECT ExamId FROM UserExam where UserId = @UserId 
    INTERSECT
    SELECT ExamId FROM Paper u2 JOIN UserPaper uu2 ON uu2.PaperId = u2.Id
    WHERE uu2.UserId = u.id)
    I) = (SELECT COUNT(*) c FROM UserExam where UserId = @UserId)