开发者

Optimising a MySQL select query to get a single random row with where clauses

I have the following table (contains over a million rows):

**MyTable**
id - int(10) 
externalId - smallint(5)
description - varchar(250)
status - smallint(6)
entrydate - int(10) (unix timestamp)

I would like to be able to select a single random row开发者_开发百科 (I only need the id value in the resultset) from this table with the following where clause:

/* The number of external ids here can range from 1 to around 50 */
WHERE externalId in (1,2,3,4,x,x,x)
/* Status is fixed at 2 for all calls */
AND status = 2
/* Entry date is typically (now - 30 days) or may be excluded all together */
AND entrydate > 1279887765

The obvious solution is to use rand() however I have found that the performance of this is somewhat lacking and this is fairly well documented. So does anybody have any alternative solutions?

To give a little background: I intend to use this query on a PHP driven website and the input parameters depend on the user so these will change from user to user. It is also worth mentioning that I cannot change the table structure at all.

Thanks in advance.


When you say, you use PHP, why not do it with the language?

Say you know you have 100.000 rows, generate a random number in PHP that's within this range, and perform a LIMIT query

SELECT * FROM mytable ORDER BY id LIMIT $randomNumber, 1; 


You could do two queries - one to get the count of total possible rows, then use that count to generate a random integer from zero to ($count - 1) in PHP, and then add "LIMIT $rand, 1" to the end of the second query.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜