简体   繁体   中英

How do I SELECT and COUNT rows in SQL?

How do I get the results and count the results in one query ? (Im using PDO statements)

SELECT * FROM table; // gets results
SELECT COUNT(*) FROM table; // counts results
$result = mysql_query( "SELECT * FROM table");
$count = mysql_num_rows( $result);

Using PDO:

$statement = $dbh->prepare('SELECT * FROM table');
$statement->execute();
$count = $statement->rowCount();

This will put the record count at the end of each row.

SELECT *
   , COUNT(1) OVER () AS RecordCount
FROM table;
SELECT *, (select count(*) FROM table) ct FROM table

you should execute only one query...

$sql = SELECT * FROM table;
$res = mysql_query($sql);

you can have total count by mysql_num_rows(); function.. like this ..

$count = mysql_num_rows($res);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM