我有以下sql需要1或2秒才能返回结果。我在游标中调用这个SQL 500多次。我正在尝试重新编写此查询。
SET @row_num=0;
SELECT * FROM
(SELECT @row_num:=@row_num+1 AS `row_num`, t_table.* FROM t_table WHERE type_id>0 ORDER BY type_id ASC, type_place_id DESC, user_id DESC LIMIT 100) AS counted_view WHERE counted_view.row_num = {$current + 1};
请建议我如何以更好的方式重新编写此查询
答案 0 :(得分:1)
不要过滤功能结果。找到替换它的方法:
AND month(OTDate) = Month(@FromDate)
AND year(OTDate) = Year(@FromDate)
这样的事情:
and OTDate >= the first day of the month for @FromDate
and OTDate < the first day of the month following @FromDate
答案 1 :(得分:0)
首先,重新编写WHERE
子句,如下所示:
SELECT . . .
FROM tbl_OTAuthorization
WHERE EmployeeCodeFK = @EmployeeCode AND
OTDate >= DATEADD(day, 1 - DAY(@FromDate), @FromDate) AND
OTDate < DATEADD(month, 1, DATEADD(@FromDate, 1 - DAY(@FromDate), @FromDate));
其次,为表创建适当的索引:
CREATE INDEX tbl_OTAuthorization_2 ON tbl_OTAuthorization(EmployeeCodeFK, OTDate, UpdatedAdjustedOT);
第三,返回并修复您的代码,使其不会在员工和日期之间循环。您应该能够在单个查询中处理逻辑。通常,如果要优化使用数据库的性能,请避免使用游标。
答案 2 :(得分:0)
试试这个:
SELECT Sum(CONVERT(DECIMAL(18, 2), ISNULL(NULLIF(UpdatedAdjustedOT, ''), 0))) as OTHours
FROM tbl_OTAuthorization
WHERE EmployeeCodeFK = @EmployeeCode
AND month(OTDate) = Month(@FromDate)
AND year(OTDate) = Year(@FromDate)
答案 3 :(得分:0)
WHERE EmployeeCodeFK = @EmployeeCode
AND OTDate >= DATEADD(MONTH, DATEDIFF(MONTH, 0, @FromDate), 0)
AND OTDate < DATEADD(MONTH, 1, DATEADD(MONTH, DATEDIFF(MONTH, 0, @FromDate), 0))