奇怪的用逗号连接

时间:2021-02-26 16:04:03

标签: sql sql-server tsql

我在看别人的代码,发现这个奇怪的连接:

SELECT 
SUM(
    (
      intUnitOverheadCost + intUnitLaborCost + intUnitMaterialCost + intUnitSubcontractCost 
      + intUnitDutyCost + intUnitFreightCost + intUnitMiscCost
    ) 
    * 
    (
            (
                CASE 
                    WHEN imtSource = 3
                        THEN - 1
                    ELSE 1
                END
            ) * intQuantity
    )
)
FROM PartTransactions               --imt
INNER JOIN PartTransactionCosts     --int
    ON imtPartTransactionID = intPartTransactionID
LEFT JOIN Warehouses                --imw
    ON imtPartWarehouseLocationID = imwWarehouseID
        , ProductionProperties      --xap <-- weird join
WHERE imtJobID = jmpJobID
AND imtSource IN (2,3)
AND imtReceiptID = ''
AND Upper(imtTableName) <> 'RECEIPTLINES'
AND imtNonInventoryTransaction <= {?CHECKBOXGROUP_4_ShowNonInventory}
AND imtJobType IN (1, 3)
AND imtTransactionDate < DATEADD(d, 1, {?PROMPT_1_TODATE})
AND (
    imtNonNettable = 0
    OR (
        imtNonNettable <> 0
        AND ISNULL(imwDoNotIncludeInJobCosts, 0) = 0
        )
    )
AND intCostType = (
    CASE -- Always 1
        WHEN xapIMCostingMethod = 1
            THEN 1
        WHEN xapIMCostingMethod = 2
            THEN 2
        WHEN xapIMCostingMethod = 3
            THEN 3
        ELSE 4
    END
)

ProductionProperties 表中只有一条记录,select xapIMCostingMethod from ProductionProperties 的结果始终为 1。

PartTransactionCosts 中总是有 4 个枚举结果,但只允许有 1 个结果。

ProductionProperties.xapIMCostingMethod 隐式加入 PartTransactionCosts.intCostType

我的具体问题是这个逗号连接到底发生了什么?看起来它必须是一个交叉连接,后来在 WHERE 子句中过滤了一个可能的结果。

1 个答案:

答案 0 :(得分:0)

同意前面的回答。这是一个笛卡尔连接,但由于行数为 1,因此不会导致问题。

我在想,如果您向 ProductionProperties 添加了行,那么它将作为您总和的乘数。我做了一个小实验来说明这个问题:

declare @tableMoney table (
unit int,
Product char(5),
xapIMPCostingMethod int,
Cost money
)
declare @tableProdProperties table (
xapIMPCostingMethod int
)

insert @tableMoney (unit, Product, xapIMPCostingMethod, Cost)
values
(1,'bike',1, 2.00),
(1,'car',1, 2.25),
(2,'boat',2, 4.50)

insert @tableProdProperties (xapIMPCostingMethod)
values (1),
(2)


select sum(Cost)
from @tableMoney, @tableProdProperties

我也不喜欢在不清楚什么加入什么的情况下使用连接,所以我总是使用别名:

select sum(Cost)
from @tableMoney tbm join @tableProdProperties tpp
on tbm.xapIMPCostingMethod = tpp.xapIMPCostingMethod
相关问题