SQL /查询字符串不返回我知道存在的记录

时间:2017-04-24 16:13:47

标签: sql ms-access

我的Access数据库中当前有一个表和一个查询。 每个人都完成了一项工作(All Folks Ever Finished)以及他们完成的工作。 我有一个查询已经搜索了另一个表,以找出此表中的哪些人已经开始了另一项工作(在另一个课程中活跃的人)。

现在我想再运行一个查询来提取已完成工作的人员的姓名,但在他们开始下一门课程时将其排除在查询中。

我已经汇总了一个查询但是当我知道它应该时,它不会返回任何记录。

SELECT
    [All Folks Ever Finished].Level
   ,[All Folks Ever Finished].Status
   ,[All Folks Ever Finished].Fname
   ,[All Folks Ever Finished].Sname
   ,[All Folks Ever Finished].Email
   ,[People who are active on another course].[All Folks Ever Active].Level
FROM
    [All Folks Ever Finished]
INNER JOIN [People who are active on another course]
    ON [All Folks Ever Finished].Email = [People who are active on another course].Email
WHERE
    NOT ( [All Folks Ever Finished].Email ) = ( [People who are active on another course].Email );

我知道2.5k中至少有1k的记录应该在完成后回来,但没有开始另一个课程。

3 个答案:

答案 0 :(得分:2)

您的inner join条件与where子句相反,因此您不会获得任何行。如果您有不同的on子句,那么您可能可以返回一些行。

要查找第一个查询/表中不在第二个查询/表中的人员,您可以使用left join并返回第二个表为null的行。

SELECT 
   [All Folks Ever Finished].level
 , [All Folks Ever Finished].status
 , [All Folks Ever Finished].Fname
 , [All Folks Ever Finished].Sname
 , [All Folks Ever Finished].Email
 , [People who are active on another course].[All Folks Ever Active].level
from [All Folks Ever Finished]
  left join [People who are active on another course] 
    on [All Folks Ever Finished].Email = [People who are active on another course].Email
where [People who are active on another course].Email is null;

答案 1 :(得分:2)

您的查询可简化如下:

SELECT A.*, B.*
FROM A INNER JOIN b
ON A.Email = B.Email
WHERE Not (A.Email) = (B.Email);

这样可以很容易地看到问题:您正在加入电子邮件,然后根据WHERE子句中的相同字段删除记录。这将始终为您提供空集,即没有记录。

据我所知,你想要的人:

  1. 谁完成了一些工作,
  2. 谁不积极参加其他课程。
  3. 有几种方法可以做到这一点。一个是使用外连接:

    SELECT A.*. B.*
    FROM A LEFT OUTER JOIN B
    ON A.Email = B.Email
    WHERE B.Email is NULL
    

    这可以通过执行外部联接并仅选择已完成工作的人员完成工作的条目为空。

    您也可以使用设置差异来执行此操作,例如: MINUS:

    SELECT A.*
    FROM A
    MINUS
    SELECT A*
    FROM A INNER JOIN B
    ON A.Email = B.Email
    

答案 2 :(得分:1)

试试这段代码:

SELECT [All Folks Ever Finished].Level, [All Folks Ever Finished].Status, [All Folks Ever Finished].Fname, [All Folks Ever Finished].Sname, [All Folks Ever Finished].Email, [People who are active on another course].[All Folks Ever Active].Level
FROM [All Folks Ever Finished] LEFT JOIN [People who are active on another course] ON [All Folks Ever Finished].Email = [People who are active on another course].Email
WHERE ([People who are active on another course].Email is null);