select语句中有和没有主键列的结果不同。为什么?

时间:2013-10-08 21:38:27

标签: sql union

我有一个Query,当我在选择列表中有主键时会返回两个不同的结果,而当主键不存在时会返回另一个结果。

以下是使用主键'FDReciptNo'的查询。

使用Primary键结果是(3478)记录,在内部select语句的select语句中没有主键我有1274条记录。

想了解为何会有这样的差异?

SELECT SUM(PrincipleAmount) AS PrincipleAmount FROM
(
    SELECT  
            FDReceiptNo, PrincipleAmount
    FROM mFixedDeposit
    WHERE   CurrentStatus = ' ' AND 
            DepositDate <= '9/20/2013 12:00:00 AM' AND 
            FDReceiptNo NOT IN
            (
                SELECT FDReceiptNo FROM mFixedDeposit 
                WHERE 
                    TransactionDate > '9/20/2013 12:00:00 AM' AND MaturityDate <= '9/20/2013 12:00:00 AM'
            )

    UNION   
    SELECT  
            FDReceiptNo, PrincipleAmount
    FROM mFixedDeposit
    WHERE   TransactionDate > '9/20/2013 12:00:00 AM' AND 
            MaturityDate <= '9/20/2013 12:00:00 AM'

) AS tbl

2 个答案:

答案 0 :(得分:11)

UNION也会执行DISTINCT,因此如果没有PK,您会多次出现其余列,这些将减少为一个。

尝试UNION ALL,这并不意味着DISTINCT

答案 1 :(得分:0)

作为geomagas pointed out,UNION存在隐式DISTINCT,但由于涉及相同的表和字段,因此您只需使用OR即可。这也允许您删除内联视图

SELECT
    SUM(PrincipleAmount) AS PrincipleAmount     
FROM mFixedDeposit
WHERE   (CurrentStatus = ' ' AND 
        DepositDate <= '9/20/2013 12:00:00 AM' AND 
        FDReceiptNo NOT IN
        (
            SELECT FDReceiptNo FROM mFixedDeposit 
            WHERE 
                TransactionDate > '9/20/2013 12:00:00 AM' AND MaturityDate <= '9/20/2013 12:00:00 AM'
        ))
        OR
        (
           TransactionDate > '9/20/2013 12:00:00 AM' AND 
           MaturityDate <= '9/20/2013 12:00:00 AM'
        )