我尝试对数据库表进行排序,然后选择第5个条目。
我有下面的代码,但这个dosnt似乎给了我正确的价值任何人都可以帮忙吗?
OleDbCommand com12 = new OleDbCommand(@"SELECT TOP 5 [Flight_Date]
FROM Flights
WHERE [Claimed_By_ID] = ?
AND [Flight_Date] <= ?
AND [Flight_Date] >= ?
ORDER BY [Flight_Date] DESC", Program.DB_CONNECTION);
com12.Parameters.Add(new OleDbParameter("", p.ID));
com12.Parameters.Add(new OleDbParameter("", DateTime.Today));
com12.Parameters.Add(new OleDbParameter("", DateTime.Today.AddMonths(-6)));
OleDbDataReader dr12 = com12.ExecuteReader();
答案 0 :(得分:2)
您可以将查询包装在另一个查询中:
SELECT MIN([Flight_Date]) AS [Flight_Date_5]
FROM (SELECT TOP 5 [Flight_Date]
FROM Flights
WHERE [Claimed_By_ID] = ?
AND [Flight_Date] <= ?
AND [Flight_Date] >= ?
ORDER BY [Flight_Date] DESC) AS [Top5]
这将返回第五高的参赛作品。如果总条目少于5个,则返回最低条目。
答案 1 :(得分:0)
使用DataTable
,将其填入您的阅读器,然后使用LINQ
获取第五条记录:
DataTable dt = new DataTable();
dt.Load(com12.ExecuteReader());
var fifthRow = dt.AsEnumerable().Skip(4).First();
答案 2 :(得分:0)
很抱歉这只是SQL Server。它不适用于MYSQL。
使用CTE是另一种正确的方法:
WITH AllData AS
(
SELECT TOP 5 ROW_NUMBER() OVER (order by [Flight_Date] DESC) as RowNumber
FROM Flights
WHERE [Claimed_By_ID] = ?
AND [Flight_Date] = ?
)
SELECT * FROM AllData WHERE RowNumber = 5
如果没有5行,则不会返回任何内容。
答案 3 :(得分:0)
MySQL没有TOP
。使用LIMIT
...
SELECT [Flight_Date]
FROM Flights
WHERE [Claimed_By_ID] = ?
AND [Flight_Date] <= ?
AND [Flight_Date] >= ?
ORDER BY [Flight_Date] DESC
LIMIT 4, 1