How to select first and last data row from a mysql result?
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.
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.
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
Assuming you have 'id' as a primary key and you need the last one (not the 75th one) you could try something like:
SELECT * FROM User WHERE id IN ((SELECT min(id) FROM user b), (SELECT max(id) FROM user c))
SELECT
(SELECT column FROM table WHERE [condition] ORDER BY column LIMIT 1) as 'first',
(SELECT column FROM table WHERE [condition] ORDER BY column DESC LIMIT 1) as 'last'
SELECT u.*
FROM Users u
INNER JOIN (
SELECT MIN(UserID) AS UserID FROM Users
UNION ALL SELECT MAX(UserID) FROM Users
) um ON um.UserID = u.UserID
Edit
I'm not sure I completely understand what you need but following gets the first and last user followed by everyone else.
SELECT um.SortOrder, u.*
FROM Users u
INNER JOIN (
SELECT 1 AS SortOrder, MIN(UserID) AS UserID FROM Users
UNION ALL SELECT 2, MAX(UserID) FROM Users
) um ON um.UserID = u.UserID
UNION ALL
SELECT 3 AS SortOrder, u.*
FROM Users u
LEFT OUTER JOIN (
SELECT MIN(UserID) AS UserID FROM Users
UNION ALL SELECT MAX(UserID) FROM Users
) um ON um.UserID = u.UserID
WHERE um.UserID IS NULL
ORDER BY
SortOrder
Well, the title of your question is a bit different from the explanation you gave.
I say so cos if you want to select first and last row, it might be different to select 1st and 75th row cos in case the rows increase or reduce, the last might not be the 75th row.
To answer the part of the first and last row, i think you can do this.
select distinct(id) from users where id in ((select max(id) from user), (select min(id) from users));
This query will work well in the hope that users are ordered by id.
But if you are talking about the 1st and 75th row, then i'll settle with @Saul's answer .
Hope this helps.
精彩评论