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?
Try this:
Edit:
It is not clear whether you want the first or last 5. If you want the last five then the order by should be:
As you are working with MySQL, why not use the
LIMIT
clause, to only keep the first 5 results ?Quoting a portion of the manual page for
select
:I am confuse with your title, and your question body. You mentioned last 5 records. in the first sentence of your question, it is first 5. A few words later, it is last 5 again.
If you want to get last 5, you may use this
if you need to take care of less than 5 total records, you need to use the following:
If you can use stored procedure, the performance will be faster when you are in the 2nd example.
Try this query