想象一下,我有一个包含大量数据的数据库,用户可以从中进行搜索。
典型搜索的结果一般在 20-100 行左右,然后进行分页(每页 20 行)。
我已经想到了两种方法来处理这些页面的导航,并且想知道这些方法是否有任何优点和/或缺点,以及是否有更好的选择。
查询一次,将结果存储在
$_SESSION
变量中并根据当前页面过滤行。我想出这个的原因是为了使数据检索一次,而不必为用户导航的每个页面连接到数据库。我不知道它是否比我想出的其他选择更好或更差。session_start(); $search = rawurldecode($_GET['search']); //search word $interval = rawurldecode($_GET['interval']); //rows per page $page = rawurldecode($_GET['page']); //page $min_row = $interval * ($page-1)+1; $max_row = $interval * $page; //query if (no results stored or first page) && the current search is not the previous search if((empty($_SESSION['SEARCH_RESULTS']) || $page == 1) && $_SESSION['SEARCH_RESULTS']['TERM'] != $search){ $_SESSION['SEARCH_RESULTS'] = array(); $_SESSION['SEARCH_RESULTS']['TERM'] = $search; $query = "exec usp_Search '$search'"; $dbh = new DBH; $dbh->Connect()->Query($query); while($row = $dbh->Fetch_Array()){ $_SESSION['SEARCH_RESULTS']['ROWS'][] = $row; } } for($j = 0; $j < count($_SESSION['SEARCH_RESULTS']['ROWS']); $j++){ $row = $_SESSION['SEARCH_RESULTS']['ROWS'][$j]; //ignore all other rows not on the page if($j < ($min_row-1) || $j > $max_row) continue; //print stuff }
逐页查询。查询和分页非常简单。
//Query $search = rawurldecode($_GET['search']); $interval = rawurldecode($_GET['interval']); $page = rawurldecode($_GET['page']); $min_row = $interval * ($page-1)+1; $max_row = $interval * $page; $query = "exec usp_Search '$search', $min_row, $max_row"; $dbh = new DBH; $dbh->Connect()->Query($query); while($row = $dbh->Fetch_Array()){ //print stuff }
备选方案中的 SQL 过程
只是一个带有 SELECT 查询的过程
SELECT COL1, COL2, COL... FROM TABLE1 WHERE ( COL1 LIKE '%'+@search+'%' OR COL2 LIKE '%'+@search+'%' OR COL... LIKE '%'+@search+'%' )
是一个创建临时表然后从变量开始到结束选择行的过程。
SELECT COL1, COL2, COL..., ROW_NUMBER() OVER (ORDER BY COL1) AS [ROW_NUMBER] INTO #result FROM TABLE1 WHERE ( COL1 LIKE '%'+@search+'%' OR COL2 LIKE '%'+@search+'%' OR COL... LIKE '%'+@search+'%' ) SELECT COL1, COL2, COL... FROM #result WHERE ROW_NUMBER BETWEEN @row_start AND @row_end