MySQL RAND() Without Repeating a Value in a Specific Column
I'm trying to Select a random set of results (5 results) from a table without selecting two notes from the same user and ordering those开发者_开发知识库 results based on date added and having the record added within 30 days. For example, let's say my table has the following columns:
user_notes
-note_id
-user_id
-note
-note_added
I'm pretty close with
SELECT * FROM
(
SELECT * FROM user_notes
WHERE note_added > date_sub(note_added,interval 30 day)
GROUP BY user_id
ORDER BY RAND()
) user_notes
ORDER BY note_added DESC LIMIT 0,5
I feel like the group by statement is screwing things up and while a user may have a record added within the last 30 days I'm just getting the first record they create due to the group by. Any suggestions?
I could not test it but for me it looks fine except the date_sub()
: Shouldn't it be
date_sub(now(),interval 30 day)?
Whether you want the random records for a specific user or not? if yes means, you can add one more condition to where clause like Specific user_id. Try it....
SELECT * FROM
(
SELECT * FROM user_notes
WHERE note_added > date_sub(note_added,interval 30 day)
ORDER BY RAND()
) user_notes
GROUP BY user_id
ORDER BY note_added DESC LIMIT 0,5
Try this and take a look at the answer from sw0x2A
精彩评论