简体   繁体   中英

Show unique random records within LIMIT

NOTE: The possible duplicate mysql RAND() LIMIT did not address the answer because in my sql my ORDER BY and LIMIT already are together.

I'd like to show unique random records but within a range, but when I use RAND() in my sql it pulls random records from beyond my limit range:

SELECT DISTINCT cases.caseid, cases.img, casetypes.casetypeid, cases.cost
FROM cases, casetypes
WHERE cases.caseid =  casetypes.caseid AND casetypes.mastercaseid = $mastercaseid
ORDER BY RAND()
LIMIT $lastrow, $perPage

EDIT: This worked for me based on answer below:

SELECT * FROM (
SELECT DISTINCT cases.caseid, cases.img, casetypes.casetypeid, cases.cost
FROM cases, casetypes
 WHERE cases.caseid =  casetypes.caseid AND casetypes.mastercaseid = $mastercaseid
 LIMIT $lastrow, $perPage
 ) x
ORDER BY RAND()

If I understand your question correctly, one option is to do a subselect so that you can do the limit before your do the order by:

SELECT * FROM (

SELECT DISTINCT cases.caseid, cases.img, casetypes.casetypeid, cases.cost
FROM cases, casetypes
WHERE cases.caseid =  casetypes.caseid AND casetypes.mastercaseid = $mastercaseid
LIMIT $lastrow, $perPage
) x

ORDER BY RAND()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM