How to count all records but only retrieve (LIMIT) a specific number for display?

后端 未结 4 1025
我在风中等你
我在风中等你 2021-01-13 12:29

I want to echo only the first 10 rows, but I need to count the total number of rows affected by the query.

I was doing a LIMIT 10 and then counting with

相关标签:
4条回答
  • 2021-01-13 12:42

    It's pretty standard to issue two queries, one selecting the desired columns with the limit clause and another selecting only a count with no limit.

    For example

    $countQuery = 'SELECT COUNT(1) FROM Badges WHERE UID = ?';
    $limitQuery = 'SELECT * FROM Badges WHERE UID = ? ORDER BY `Date` DESC LIMIT 0, 10';
    
    0 讨论(0)
  • 2021-01-13 12:46

    MySQL has some special support for this sort of thing. First, include SQL_CALC_FOUND_ROWS in your SELECT:

    SELECT SQL_CALC_FOUND_ROWS *
    FROM Badges
    WHERE UID = '$user'
    ORDER by Date DESC
    LIMIT 10 -- Or whatever
    

    Then pull out your rows and then immediately look at FOUND_ROWS() like this:

    SELECT FOUND_ROWS()
    

    to get the number of rows that matched your original query without considering the LIMIT clause.

    This is MySQL-specific but it should be a little faster than doing two queries.

    0 讨论(0)
  • 2021-01-13 13:02

    You have to make 2 queries: the first one will count all rows, the second one will return 10 rows:

    $count = 0;
    $query = "SELECT count(*) as count FROM Badges WHERE UID = '$user'";
    $rs = mysql_query($query);   
    
    if (mysql_errno() == 0)
    {
        $r = mysql_fetch_object($rs);
        $count = $r->count;
    }
    
    if ($count > 0)
    {
        $query = "SELECT * FROM Badges WHERE UID = '$user' ORDER by Date DESC LIMIT 10";
        $rs = mysql_query($query);      
    
        if (mysql_errno() == 0)
        {            
            while ($r = mysql_fetch_array($rs))       
            {       
                echo $r['Site']; 
            }     
        }
    }
    
    0 讨论(0)
  • 2021-01-13 13:08

    count all records

    $data = mysql_query("SELECT * FROM Badges WHERE UID = '$user' ORDER by Date DESC");
    $count = mysql_num_rows($data);
    echo "No of Records is :" . $count;
    

    print 10 records...

     $data = mysql_query("SELECT * FROM Badges WHERE UID = '$user' ORDER by Date DESC LIMIT 0, 10");
        while($row = mysql_fetch_array( $data )) 
            { 
            echo $row['Site'];
            }
    
    0 讨论(0)
提交回复
热议问题