0

I would like get number of records in a table then divide them by 4, after dividing them by 4 i want to create sql statements with limit ranges based on my result. For example I have a table with 8 records I divide by 4, I will create 2 sql statements with a limit range like limit 0,4 and limit 4,8

Final results will look like

Select * from prop where id=123 LIMIT 0,4

Select * from prop where id=123 LIMIT 4,8

My approach was to have for loop which will count the number of sql statements to be made. Then in the loop: first circle 0-4 and second will be 4-8

Am struggling on the limit 0-4 and limit 4-8

PHP script

include('connect.php');    
$query_1 = "Select COUNT(*) as Total from prop where ref = 'SB2004'";
$results_query_1 = mysql_query($query_1);
 while($row_query_1 = mysql_fetch_array($results_query_1))
 {
        $cnt = $row_query_1['Total'];
 }

 echo $cnt;
 echo "<br>";
 $num_grps = 0;
 if ($cnt % 4 == 0 )
 {
   echo $num_grps = $cnt / 4 ;

 }
$count_chk= $num_grps * 4;
 for ($i=1;$i<=$num_grps;$i++)
{
    //for loop for range
    for()
    {
        $range = '0,4';
        echo "SELECT prop_ref from prop limit".$range;
    }
}
4

1 回答 1

0

要么你没有理解这个问题,要么没有很好地解释它。

这里最直接的问题是您误解了 LIMIT 子句的语法。第一个参数指定要开始的偏移量,第二个参数定义要返回的行数,因此 LIMIT 4,8 将返回 8 行(假设数据集中有 12 行或更多行)。

下一个问题是您没有说结果是否需要可重现 - 例如,如果您有主键 1 和 2 的行,是否应该始终在同一个查询中返回这些行。在没有显式 ORDER BY 子句的情况下,将根据查询找到它们的顺序返回行。

下一个问题是,当总行数不是 4 的偶数倍时,您还没有解释如何处理最后一种情况。

您提供的代码会计算行数,where ref = 'SB2004'但会创建未过滤的查询 - 为什么?

您提供的代码不会更改查询中的限制 - 为什么?

下一个问题是,在这样的循环中运行 SELECT 查询永远没有充分的理由。你没有解释你打算用选择查询做什么。但是根据后续的更新......

 include('connect.php');    
 $query_1 = "Select COUNT(*) as Total from prop where ref = 'SB2004'";
 $cnt = mysql_fetch_assoc(mysql_query($query_1));

 $blocks=$cnt['Total']/4 + (0 == $cnt['Total'] % 4 ? 0 : 1);

 $qry2="SELECT * FROM prop where ref='SB2004' ORDER BY primary_key";
 $res=mysql_fetch_assoc($qry2);

 for ($x=0; $x<$blocks; $x++) {
    print "<div>\n$block<br />\n";
    for ($y=0; $y<4; $y++) {
       print implode(",", @mysql_fetch_assoc($res)). "\n";
    }
    print "</div>\n";
 }

进一步细化这一点以仅向数据库发出单个查询是微不足道的。

如果你真的必须生成单独的 SELECT ......

 include('connect.php');    
 $query_1 = "Select COUNT(*) as Total from prop where ref = 'SB2004'";
 $cnt = mysql_fetch_assoc(mysql_query($query_1));

 $blocks=$cnt['Total']/4 + (0 == $cnt['Total'] % 4 ? 0 : 1);

 for ($x=0; $x<$blocks; $x++) {
       $y=$x*4;
       print "SELECT * FROM prop where ref='SB2004' 
           ORDER BY primary_key LIMIT $y,4<br />\n"
 }
于 2013-10-30T12:51:14.797 回答