问题
Hi again people of stackoverflow. I have a routine that has a step that I find unnecessary lets say you want to get all the images from a gallery, and limit a certain number of images per page.
$db = PDO object
$start = (pagenum x images per page)
$limit = (images per page)
$itemsdata = $db->query("SELECT id,name FROM gallery LIMIT $start,$limit")->fetchAll();
$numitems = $db->query("SELECT id FROM gallery")->rowCount();
$imgsdata
is a array of all the images in a gallery for example.
$numimgs
is the number of images that the gallery has.
you would need $imgsdata
to do a foreach loop on each image in the array, while
$numimgs
is needed to generate the page numbering (e.g. << 1 2 3 4 >>)
my grudge is with $db->query("SELECT id FROM gallery")->rowCount();
It feels completely like some sort of cheat, isn't there a direct way to get the number of rows in a table, something like SELECT gallery.Rows
?
p.s. currently I'm using SQLite, but I'd need it for MySQL and PostgreSQL as well.
回答1:
This will tell you the number of rows:
SELECT COUNT(*) FROM gallery
回答2:
A simple count() aggregate function will return the number of rows quickly
Select count(*) from table
回答3:
select count(*) from gallery
回答4:
Me too!
SELECT COUNT(*) FROM gallery
Yes, this should work the same just fine in MySQL, SQLite, and PostgreSQL.
来源:https://stackoverflow.com/questions/3408669/sql-direct-way-to-get-number-of-rows-in-table