在SQL中达到LIMIT的其他替代方法

时间:2018-07-26 09:26:10

标签: sql sql-server codeigniter datatable

我创建了一个SQL查询来获取带有LIMIT的某些数据,因此可以在datatable中使用它。它有76288行。

SELECT TransDate, AgentName, OfficeCode, year, ControlNumber, 
       ContainerNumber, BookingNumber, SealNumber, VesselName, ShippingLine, ShippingDate
FROM (
       SELECT a.TransDate, a.AgentName, a.OfficeCode, DATEPART(YEAR, a.TransDate) AS year, 
              a.ControlNumber, b.ContainerNumber, b.BookingNumber,
              b.SealNumber, b.VesselName, b.ShippingLine, b.ShippingDate,
              ROW_NUMBER() OVER (ORDER BY a.TransDate) R
       FROM Cargo_Transactions a 
       JOIN Cargo_Vessels b ON a.ControlNumber = b.ControlNumber 
       LEFT OUTER JOIN [Routes] c ON a.RouteID = c.RouteID
       WHERE 
              a.TransDate IS NOT NULL 
              AND a.TransDate <= GETDATE() 
              AND DATEPART(YEAR, a.TransDate) = '2018'
) as f WHERE R BETWEEN 0 and 100
ORDER BY TransDate ASC;

0和100位于单击分页时会更改的变量内。

如果用于前一百页,则加载正常。但是,当我单击最后一页时,它说超时已超出。另外,当我使用数据表的搜索功能时,它无法正常工作。

示例:我在数据表中搜索了dino,它将说它有95条记录,但是由于查询仅在0到10之间,因此只会显示1条记录。

SELECT TransDate, AgentName, OfficeCode, year, ControlNumber, ContainerNumber, 
       BookingNumber, SealNumber, VesselName, ShippingLine, ShippingDate
FROM (
       SELECT a.TransDate, a.AgentName, a.OfficeCode, DATEPART(YEAR, a.TransDate) AS year, 
              a.ControlNumber, b.ContainerNumber, b.BookingNumber, b.SealNumber, 
              b.VesselName, b.ShippingLine, b.ShippingDate,
              ROW_NUMBER() OVER (ORDER BY a.TransDate) R
       FROM Cargo_Transactions a 
       JOIN Cargo_Vessels b ON a.ControlNumber = b.ControlNumber 
       LEFT OUTER JOIN [Routes] c ON a.RouteID = c.RouteID
       WHERE 
              a.TransDate IS NOT NULL 
              AND a.TransDate <= GETDATE() 
              AND DATEPART(YEAR, a.TransDate) = '2018'
) as f WHERE R BETWEEN 0 and 10 AND AgentName LIKE '%dino%'
ORDER BY TransDate ASC;

我也尝试了TOPEXCEPT,但是当我搜索SELECT TOP 0... EXCEPT SELECT TOP 100...时,它仅显示9行。

更新:

我能够通过在子查询中包含WHERE子句来使其工作。我现在唯一的问题是ORDER BY。它仅在显示的当前页面(数据1-10)中有效,而对所有数据均无效。

还有其他选择吗?非常感谢您的帮助。谢谢!

0 个答案:

没有答案