如何将过滤器添加到联接表

时间:2019-08-21 11:17:43

标签: sql sql-server sql-server-2012

我有此查询,该查询可以正常工作。它返回所有行,并在可能的情况下连接两个表。

现在,我要取消注释最后两行,以便联接的表仅包括IsPrimary = 1的那些记录。(如果IsPrimary = 0,则我不想进行联接,并且列应为null。)

当我取消注释这些行时,它将停止返回Organization表中的所有行。

如何修改此查询以使其正常工作?

Select top (Select ts.MaxRecords
 from TableSettings ts
 where ts.TableName = 'Organization') 
            O.*,
            L.Name,
            ISNULL(C.FirstName, '') + ' ' + IsNull(C.LastName, '') as FullName

        FROM [dbo].[Organization] O 
        left join Location l on l.OrganizationId = o.Id
        left join Contact c on C.LocationId = l.Id

        WHERE
        O.TenantId = @tenantId and
        (@id IS NULL OR O.Id  = @Id) AND
        (@name IS NULL OR O.Name LIKE '%' + trim(@Name) + '%') AND
        (@organizationTypeId IS NULL OR O.OrganizationTypeId = @organizationTypeId) 
        --and l.IsPrimary = 1 and
        --C.IsPrimary = 1

2 个答案:

答案 0 :(得分:2)

将您的条件从where子句移至联接。

对于内部联接,它们是等效的,但是对于左联接,它是空结果与无结果之间的差异。

答案 1 :(得分:0)

 Select top (Select ts.MaxRecords
 from TableSettings ts
 where ts.TableName = 'Organization') 
        O.*,
        L.Name,
        ISNULL(C.FirstName, '') + ' ' + IsNull(C.LastName, '') as FullName

    FROM [dbo].[Organization] O 
    left join Location l on l.OrganizationId = o.Id and l.IsPrimary = 1
    left join Contact c on C.LocationId = l.Id and C.IsPrimary = 1

    WHERE
    O.TenantId = @tenantId and
    (@id IS NULL OR O.Id  = @Id) AND
    (@name IS NULL OR O.Name LIKE '%' + trim(@Name) + '%') AND
    (@organizationTypeId IS NULL OR O.OrganizationTypeId = @organizationTypeId)