2012-12-25 39 views
-1

行返回子在我的Web应用程序之一,我需要证明从MySQL结果作为列表(共6个)与环绕

在点击“Next”按钮,需要显示未来6项成果通过Ajax调用。 再次点击“下一步”想要显示更多6个结果。 Vise verse on Previous click也。

我实现了代码和工作正常,但其余

假设只有14个匹配小逻辑要求导致

我想告诉6日开始,“下一步”我想告诉未来6, “下一步”只有2个剩余所以想显示从第一圈

即,在这种情况下想要显示剩余的2 + 4 12,14,1,2,3,4(总共6)

还有一个例子:如果有15个结果,我想要显示13,14,15,1, 2,3

请指点一下在MySQL这个逻辑一点点,PHP

+0

我只是想简单的mysql选择查询..因为这只会在“最后的下一步”显示最后2。 – ramesh

+1

考虑修改您的问题的标题,以便对问题有所了解。 – DWright

回答

2

有当然limit的,但没有内置回绕,据我所知。可能的工作是将union附加到您的主要选择。这样

select * from table limit 13, 6 
union 
select * from table limit 0, 6 

东西虽然,你必须定义一些全局order by有它正确的顺序。

另一种方法是将前六个结果行保存在某个PHP数组中,并在当前结果集太小(即小于6)时追加它们。

3

你可以做这样的事情:

$maxPerPage = 6; 
//Suppose you have 14 matched results and you are on page 3 
$remainingRecords = $totalRecords - ($maxPerPage * ($pageNum - 1)); 
if($remainingRecords < $maxPerPage) { 
    $moreToShow = $maxPerPage - $remainingRecords 
    // Union $moreToShow number of records using LIMIT $moreToShow to your SQL query 
} 

我希望帮助...

2

假设你正在使用limit让每一组行的,你可以使用

limit ($page-1)*6+1, 6 

这将返回n行。如果n是6,则返回这些行。如果是< 6,做另一个查询有:

limit 6-$n 

附加这些行第一个查询返回的行,并返回给客户端。

1

下面是一个可移植的纯粹的SQL版本,您可以使用它作为基础,替换您需要/想要的大量PHP查询构造。查询(和测试表)可在http://sqlfiddle.com/#!2/4f85a/51

SET @pagesToGet = 6; -- this and the following @variables 
--      can be replaced by stuff from php variables 
--      as you construct the query    
SET @startingPageNumber = 12; 
SET @maxPageNumber = (SELECT MAX(PageNumber) FROM Pages); 
SET @maxPageNumberToGet = LEAST(@startingPageNumber + @pagesToGet - 1,@maxPageNumber); 

SELECT pagenumber FROM 
(
    -- This is the main query 
    SELECT 'a' as ordering_field, pagenumber 
    FROM pages 
    WHERE pagenumber >= @startingPageNumber and pagenumber <= @maxPageNumberToGet 
    UNION 
    -- The following supplemental query gets pages from the beginning, 
    -- when required 
    SELECT 'b' as ordering_field, pagenumber 
    FROM pages 
    WHERE pagenumber >= 1 and pagenumber <= (@pagesToGet - (@maxPageNumberToGet - @startingPageNumber + 1)) 
) t 
ORDER BY ordering_field,pagenumber 

-- using ordering_field above ensures that the pages retrieved in 
-- supplemental query. This is necessary, since nothing guarantees 
-- the ordering from the UNION