两个查询返回不同的结果计数

时间:2015-01-29 03:20:12

标签: sql sql-server tsql

我有两个经过测试的问题:

SELECT [FirstName], [LastName], [PreferredName], [DOB], [Sex], LastActivityDate,LoweredEmail, EmailConfirmed FROM [Patients] p 
join AspNetUsers u on p.Id=u.PatientId 
join AspNetUserRoles r on u.Id=r.UserId
WHERE (p.[ClinicId] = 1) and RoleId='16874754-779a-fbae-8caf-bbbb2344b7a6'

它返回1301结果

但是这个查询

SELECT AspNetUsers.id FROM dbo.AspNetUsers 
INNER JOIN dbo.AspNetUserRoles ON AspNetUsers.Id=AspNetUserRoles.UserId 
WHERE AspNetUsers.ClinicId = 1 and AspNetUserRoles.RoleID='16874754-779a-fbae-8caf-bbbb2344b7a6'

这个返回1303

我已经尝试过此查询来检查丢失的内容并且结果为零

    SELECT [FirstName], [LastName], [PreferredName], [DOB], [Sex], LastActivityDate,LoweredEmail, EmailConfirmed FROM [Patients] p 
    join AspNetUsers u on p.Id=u.PatientId 
    join AspNetUserRoles r on u.Id=r.UserId
    WHERE (p.[ClinicId] = 1) and RoleId='16874754-779a-fbae-8caf-bbbb2344b7a6'
    and u.PatientId not in
    (
    SELECT AspNetUsers.PatientId FROM dbo.AspNetUsers INNER JOIN 
    dbo.AspNetUserRoles ON AspNetUsers.Id=AspNetUserRoles.UserId WHERE
    AspNetUsers.ClinicId = 1 and 
    AspNetUserRoles.RoleID='16874754-779a-fbae-8caf-bbbb2344b7a6'
    )

我如何找出哪个是正确的,为什么我会有所不同?

3 个答案:

答案 0 :(得分:0)

第二个查询返回1303条记录:

SELECT AspNetUsers.id
FROM dbo.AspNetUsers INNER JOIN
     dbo.AspNetUserRoles
     ON AspNetUsers.Id = AspNetUserRoles.UserId 
WHERE AspNetUsers.ClinicId = 1 and
      AspNetUserRoles.RoleID='16874754-779a-fbae-8caf-bbbb2344b7a6'

第一个查询返回1301条记录:

SELECT [FirstName], [LastName], [PreferredName], [DOB], [Sex],   
       LastActivityDate, LoweredEmail, EmailConfirmed
FROM [Patients] p join
     AspNetUsers u
     on p.Id = u.PatientId join
     AspNetUserRoles r
     on u.Id = r.UserId
WHERE (p.[ClinicId] = 1) and RoleId='16874754-779a-fbae-8caf-bbbb2344b7a6' 

这两者之间的区别在于Patients上的联接。这是inner join,因此可能会过滤结果。请注意,重复也可能导致问题。

您可以使用以下命令确定缺少的行(因为缺少一些行):

select *
from AspNetUsers nu
where not exists (select 1 from patents p where p.id = nu.PatientId);

答案 1 :(得分:0)

你试过SELECT DISTINCT吗? 另请尝试以其他方式检查查询(子查询到主查询,主查询到子查询)

答案 2 :(得分:0)

您在第二个查询中遇到重复项。第一个使用clinicid中的patient,而第二个使用来自aspusers表的clinicid。嫌疑人是aspuserspatient。检查与aspusers中的相同。要从patient

中找出差值减去{{1}}