Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select first and last data row from a mysql result?

Tags:

php

mysql

SELECT * from User returns 75 users. Is it possible to select 1st user, and 75th user without doing while($row = mysql_fetch_assoc($result)) ?? and how?

UPDATE

Just to be more clear: I need to have SELECT * as I need the first and 75th user before I do while mysql_fetch_assoc so ASC, DESC, LIMIT answers not required.

like image 943
Kay Avatar asked Feb 04 '11 14:02

Kay


2 Answers

SELECT * from User LIMIT 1
UNION
SELECT * from User LIMIT 74,1

Edit

@Kay: PHP can't change the internal order of the resultset after it's created.

If the query always returns 75 rows then the only way to access the 1st and the 75th before anything else would be to use mysql_data_seek which moves the internal result pointer:

$result = mysql_query('SELECT * from User');

mysql_data_seek($result, 1);
$row1 = mysql_fetch_assoc($result);

mysql_data_seek($result, 75);
$row75 = mysql_fetch_assoc($result);

Note that if the above is followed by a while, the pointer must be reset to a suitable position.

like image 69
Saul Avatar answered Oct 13 '22 22:10

Saul


If you can sort it, you can.

Select * from User order by [something] asc limit 1

and

Select * from User order by [something] desc limit 1
like image 34
alex Avatar answered Oct 13 '22 23:10

alex