我们可以将2个SQL与相同的逻辑合并,只是略有差异吗?

时间:2013-09-24 09:37:51

标签: sql performance tsql sql-server-2008-r2

我有2个SQL,

    SELECT  @AlreadyPerformedActionsPerDay = COUNT(*)
    FROM    UserRewardActions URA
            INNER JOIN UserRewardActionTypes URAT ON URAT.ID = URA.UserRewardActionTypeID
    WHERE   URA.UserID = @UserID
            AND (
                    @UserRewardActionTypeID = 1 -- Because the register action is not per-date-wise(only allows once in lifetime)
                    OR CreationDateInUtc BETWEEN CAST(GETUTCDATE() AS DATE) AND DATEADD(DAY, 1, CAST(GETUTCDATE() AS DATE)) -- Inside Current Date
                );

    SELECT  @AlreadyRedeemedTheCurrentAction = 1
    FROM    UserRewardActions URA
            INNER JOIN UserRewardActionTypes URAT ON URAT.ID = URA.UserRewardActionTypeID
    WHERE   URA.UserID = @UserID
            AND CreationDateInUtc BETWEEN CAST(GETUTCDATE() AS DATE) AND DATEADD(DAY, 1, CAST(GETUTCDATE() AS DATE)) -- Inside Current Date
            AND URL IS NOT NULL 
            AND URL = @Url;

第一个SQL就是今天抓取的用户操作总数。其次,检查当前URL是否已被同一用户使用。这可以。但我希望合并此查询以解决性能问题。

1 个答案:

答案 0 :(得分:1)

好了,重新格式化您的查询后如下。我可以看到他们有不同的标准。

DECLARE @from DateTime;
DECLARE @to DateTime;

SET @from  = cast(getutcdate() as Date);
SET @to = dateadd(DAY, 1, @from));

SELECT
                @AlreadyPerformedActionsPerDay = COUNT(*)
    FROM
                UserRewardActions URA
        JOIN
                UserRewardActionTypes URAT
                    ON URAT.ID = URA.UserRewardActionTypeID
        WHERE
                URA.UserID = @UserID
            AND
                (
                    @UserRewardActionTypeID = 1
                 OR 
                    CreationDateInUtc BETWEEN @from AND @to
                );

SELECT
                @AlreadyRedeemedTheCurrentAction = 1
    FROM
                UserRewardActions URA
         JOIN
                UserRewardActionTypes URAT
                    ON URAT.ID = URA.UserRewardActionTypeID
    WHERE
                URA.UserID = @UserID
        AND
                CreationDateInUtc BETWEEN @from AND @to
        AND
                URL IS NOT NULL 
        AND
                URL = @Url;