简体   繁体   中英

How to count the number of rows before a given row in MySQL with CodeIgniter?

Simply put, how can I count how many rows there are before a certain row. I'm using incremental ID's, but rows are deleted a random, so just checking to see what the ID is won't work.

If I have, say, 30 rows, and I've selected one based on a name (or anything really), how many rows are there before that one? It could be 16, 1, 12, or anything.

I'm using MySQL and CodeIgniter.

I assume your primary key column has datatype integer

SELECT COUNT(*) FROM `table`
WHERE id < (SELECT id FROM `table` WHERE `conditions are met for specific row`)

Assuming it's an auto_increment column, deleted rows won't be filled in again so this should do the job.

SELECT COUNT(*) FROM table WHERE id_column < your_selected_row_id;

On your model:

$id = $this->db->get('users')->where("name", "John")->id;
$rows = $this->db->get('users')->where("id < ", $id)->num_rows();

return $rows;

Notice how I'm using "chained methods" and for that you need PHP5 which is the default for CI 2.

You first need to get the ID of the record you need to start counting "backwards" which is the first line, considering a table called users and that the column you are filtering is "name" and the row you want to find has the name value of John.

The second line will give you the number of rows that the query "where id < number " returned where number is the ID you got from the first query. Maybe you can even chain both lines.

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