I'm trying to execute a MYSQL command which grabs all the rows with the given UserID, sorts them by date, then returns only the first 5.
The command to sort is
ORDER BY date
and the command to get the last 5 is
WHERE ROWNUM <= 5
The WHERE comes before the ORDER, so it's backwards. So I figured I have to have a Mysql statement within a mysql statement.
Here is my attempt. I was getting an alias error, so i added the AS T1 to the command.
SELECT * FROM
(SELECT voting_id, caption_uid, voting_date, rating FROM voting
WHERE user_id = $inUserID AS T1
ORDER BY voting_date)
WHERE ROWNUM <= 5 AS T2;
Any ideas?
解决方案
As you are working with MySQL, why not use the LIMIT clause, to only keep the first 5 results ?
select *
from your_table
order by your_column
limit 0, 5
The LIMIT clause can be used to constrain the number of rows
returned by the SELECT statement. LIMIT takes one or two numeric
arguments, which must both be nonnegative integer constants (except
when using prepared statements).
With two arguments, the
first argument specifies the offset of the first row to return, and
the second specifies the maximum number of rows to return.