【问题标题】:MS Access SQL pagination with a query (no unique identifier) or ROW_NUMBER?带有查询(无唯一标识符)或 ROW_NUMBER 的 MS Access SQL 分页?
【发布时间】:2016-03-09 15:29:50
【问题描述】:

我试图一次从 SQL 查询中获取 100 行并将它们用于分页。该查询从包含 100,000 多行的表中返回约 2000 行。但是,该表没有唯一标识符。

SELECT TOP 100 * FROM tbl_Items WHERE tbl_Items.Repair_Required = true

我已经研究过使用 ROW_NUMBER,但它似乎在 MS Access 中不可用。我还研究了使用 Gord Thompson 在此处回答的“自加入”创建自定义 row_number:Access query producing results like ROW_NUMBER() in T-SQL。但是,将我的 100,000+ 表与自身连接起来在性能上并不容易。

我有什么选择?

【问题讨论】:

  • 将 10 万条记录与自身连接起来应该很容易。
  • @GordThompson - 抱歉,我删除了我的评论。

标签: sql ms-access pagination self-join


【解决方案1】:

这是一个使用集合的方法,它的工作速度非常快:

Public Function RowCounter( _
  ByVal strKey As String, _
  ByVal booReset As Boolean, _
  Optional ByVal strGroupKey As String) _
  As Long

' Builds consecutive RowIDs in select, append or create query
' with the possibility of automatic reset.
' Optionally a grouping key can be passed to reset the row count
' for every group key.
'
' Usage (typical select query):
'   SELECT RowCounter(CStr([ID]),False) AS RowID, *
'   FROM tblSomeTable
'   WHERE (RowCounter(CStr([ID]),False) <> RowCounter("",True));
'
' The Where statement resets the counter when the query is run
' and is needed for browsing a select query.
'
' Usage (typical append query, manual reset):
' 1. Reset counter manually:
'   Call RowCounter(vbNullString, False)
' 2. Run query:
'   INSERT INTO tblTemp ( RowID )
'   SELECT RowCounter(CStr([ID]),False) AS RowID, *
'   FROM tblSomeTable;
'
' Usage (typical append query, automatic reset):
'   INSERT INTO tblTemp ( RowID )
'   SELECT RowCounter(CStr([ID]),False) AS RowID, *
'   FROM tblSomeTable
'   WHERE (RowCounter("",True)=0);
'
' 2002-04-13. Cactus Data ApS. CPH
' 2002-09-09. Str() sometimes fails. Replaced with CStr().
' 2005-10-21. Str(col.Count + 1) reduced to col.Count + 1.
' 2008-02-27. Optional group parameter added.

  Static col      As New Collection
  Static strGroup As String

  On Error GoTo Err_RowCounter

  If booReset = True Or strGroup <> strGroupKey Then
    Set col = Nothing
    strGroup = strGroupKey
  Else
    col.Add col.Count + 1, strKey
  End If

  RowCounter = col(strKey)

Exit_RowCounter:
  Exit Function

Err_RowCounter:
  Select Case Err
    Case 457
      ' Key is present.
      Resume Next
    Case Else
      ' Some other error.
      Resume Exit_RowCounter
  End Select
End Function

请学习嵌入式 cmets 和示例。

当然,您会将其应用于包含 2000 条记录的查询,而不是源表。

【讨论】:

    猜你喜欢
    • 2021-10-29
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-23
    • 1970-01-01
    相关资源
    最近更新 更多