2011年4月17日 星期日

Add a counter column in a query

Sometimes I’ve needed to add a counter column in a query and I don’t want to add the column with php, so I’ve found this query to put the counter directly in the record set returned out from the query.
1. set @N = 0;
2. SELECT @N := @N +1 AS number, name, surname FROM people;

To use it in PHP scripts you have to use 2 query statements:
1. mysql_query("set @N = 0;");
2. $rs = mysql_query("SELECT @N := @N +1 AS number, name, surname FROM people");
3. while ($r=mysql_fetch_array($rs)) {
4. echo $r['number']." - ".$r['name']." ".$r['surname'];
5. }

沒有留言:

張貼留言