سؤال

I've got a series of queries that I do to get 5 results at random, the problem is that it is taking a while to get through them, mostly because it involves a loop to assign a rand value that I can order by (which Railo can do in-query)

I was wondering if anyone has dealt with this and knows of a way of speeding it up.

I'm below 200ms, which isn't bad but I'm sure it can be sped up.

هل كانت مفيدة؟

المحلول

You probably don't need to use QoQ at all.

One option might be to write your original query as:

SELECT TOP 5 whatever,you,need
FROM table
ORDER BY rand()

Update the syntax depending on which database server you're using.

Another option, which could be done for both regular queries and QoQ, would be:

  1. select only the primary keys
  2. shuffle the array (i.e. createObject("java","java.util.Collections").shuffle(Array))
  3. use the first five items in the array to select the fields you need.

No looping or updating, just two simple selects.

Of course if your primary key is just an auto-incrementing integer, you might get away with SELECT MAX(Id) then use RandRange to pick your five items.

نصائح أخرى

For Microsoft SQL Server (v2005+) this query syntax will get 5 random records:

SELECT TOP 5 *
FROM table
ORDER BY NEWID()

I'm on Railo (ColdFusion 9) and neither TOP nor NEWID() works in a Query of Query (QoQ). If you happen to fall into this use case, and you must act upon a QoQ, then here's a solution:

<cfquery name="randomizedQueryObject" dbtype="query" maxrows="10">
SELECT *, RAND() as rand
FROM someQueryObject
ORDER BY rand
</cfquery>

This returns 10 random items from a larger result set and works in a QoQ. Short and simple.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top