2

我在多表上有以下查询

SELECT DISTINCT b.BoxBarcode as [Box Barcode], (select case when  b.ImagesCount IS NULL
        then 0 
        else  b.ImagesCount end) as [Total Images], s.StageName as [Current   Stage] ,d.DocuementTypeName as [Document Type],
        u.UserName as [Start User],uu.UserName as [Finished User]

FROM [dbo].[Operations] o
    inner join dbo.LKUP_Stages s on 
        o.stageid=s.id
    inner join dbo.LKUP_Users u on
        u.id=o.startuserid
    left join dbo.LKUP_Users uu on
        uu.id=o.FinishedUserID
    inner join boxes b on
        b.id=o.boxid
    inner join LKUP_DocumentTypes d on
        d.ID = b.DocTypeID 

where b.IsExportFinished = 0

当我从IsExportFinished = 0 得到 Count 42 记录的 Boxes 表中选择计数时,当我运行上面的 qoury 时,我得到了 71 条记录,我只想检索 Boxes 表中的 42 条记录。

4

3 回答 3

4

您正在执行一对多连接,即至少其中一个表有多个符合连接条件的行。

第一步是找到给出“重复”的表。

完成此操作后,您可以通过向联接添加其他条件来解决问题。我猜同样的情况在表boxid中出现了好几次。Operations如果是这种情况,您需要决定Operation要选择哪一行,然后相应地更新 SQL。

于 2013-08-07T10:34:24.460 回答
1

试试这个——

SELECT
      Box_Barcode = b.BoxBarcode
    , Total_Images = ISNULL(b.ImagesCount, 0)
    , Current_Stage = s.StageName
    , Document_Type = d.DocuementTypeName
    , Start_User = u.UserName
    , Finished_User = uu.UserName
FROM (
    SELECT DISTINCT 
          o.stageid
        , o.boxid
        , o.startuserid
        , o.FinishedUserID
    FROM dbo.[Operations]
) o
JOIN dbo.LKUP_Stages s ON o.stageid = s.id
JOIN dbo.boxes b ON b.id = o.boxid
JOIN dbo.LKUP_DocumentTypes d ON d.id = b.DocTypeID
JOIN dbo.LKUP_Users u ON u.id = o.startuserid
LEFT JOIN dbo.LKUP_Users uu ON uu.id = o.FinishedUserID
WHERE b.IsExportFinished = 0
于 2013-08-07T10:47:07.937 回答
0

我猜如果您将 LEFT JOIN 更改为 INNER JOIN,您将获得 42 条记录。

于 2013-08-07T10:30:15.360 回答