Sql 计算列的排序或筛选速度太慢
我有一个用于排序或筛选的计算列,但当有1000多行时,执行时间太长 此查询用于预订系统,以根据价格订购可用日期 以下是数据库架构:Sql 计算列的排序或筛选速度太慢,sql,sql-server,tsql,Sql,Sql Server,Tsql,我有一个用于排序或筛选的计算列,但当有1000多行时,执行时间太长 此查询用于预订系统,以根据价格订购可用日期 以下是数据库架构: AvailableDates has one DateGroup DateGroup has many Prices DateGroup has many Discounts Each Discount contains 3 columns. MinPerson, MaxPerson, DiscountPercentage AvailableDates has ma
AvailableDates has one DateGroup
DateGroup has many Prices
DateGroup has many Discounts
Each Discount contains 3 columns. MinPerson, MaxPerson, DiscountPercentage
AvailableDates has many BookingGroups.
BookingGroups has many Bookings.
BookingGroups has a computed column that calculates how many bookings there are.
AvailableDate上价格的计算列由函数计算。价格取决于价格
Get Max Price from Prices
Get How many booking there is
Get discount that will be applied depending on number of bookings.
以下是函数查询:
FUNCTION [dbo].[fn_datePrice]
(
@id INT,
@groupId INT
)
RETURNS decimal(19, 5)
AS
BEGIN
declare @price decimal(19,5), @discount decimal(19,5), @numOfPeople INT
SELECT @numOfPeople= b.NumberOfPeople FROM BookingGroup b
WHERE b.DateId = @id and b.Status != 'Expired';
if (@numOfPeople is null or @numOfPeople < 1)
SET @numOfPeople = 1;
SELECT @price = MAX(pr.Price),
@discount = disc.DiscountPercentage
FROM DateGroup dateGroup
LEFT JOIN Prices pr on pr.GroupId = dateGroup.Id
LEFT JOIN Discounts disc on disc.GroupId = dateGroup.Id and @numOfPeople BETWEEN disc.MinPeople and disc.MaxPeople
WHERE dateGroup.Id = @groupId
GROUP BY dateGroup.Id, disc.DiscountPercentage;
if (@discount is null)
return @price
return @price * (100 - @discount) / 100
END;
GO
我已尝试重新编写您的加入:
SELECT @price = MAX(pr.Price),
@discount = disc.DiscountPercentage
FROM DateGroup dateGroup
LEFT JOIN Prices pr on pr.GroupId = dateGroup.Id
LEFT JOIN Discounts disc on disc.GroupId = dateGroup.Id
WHERE (@numOfPeople BETWEEN disc.MinPeople and disc.MaxPeople)
AND (dateGroup.Id = @groupId)
GROUP BY dateGroup.Id, disc.DiscountPercentage;
请尝试让我知道它是否会产生影响。您总是可以尝试将此函数重写为内联函数,您需要记住,多行函数总是比内联函数慢得多。这能帮助您理解计算列吗?
SELECT @price = MAX(pr.Price),
@discount = disc.DiscountPercentage
FROM DateGroup dateGroup
LEFT JOIN Prices pr on pr.GroupId = dateGroup.Id
LEFT JOIN Discounts disc on disc.GroupId = dateGroup.Id
WHERE (@numOfPeople BETWEEN disc.MinPeople and disc.MaxPeople)
AND (dateGroup.Id = @groupId)
GROUP BY dateGroup.Id, disc.DiscountPercentage;