Created
April 14, 2011 13:23
-
-
Save Ocramius/919465 to your computer and use it in GitHub Desktop.
MySQL RAND() function in Doctrine2 DQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$config = new \Doctrine\ORM\Configuration(); | |
/** OTHER STUFF */ | |
$config->addCustomNumericFunction('RAND', 'My\Custom\Doctrine2\Function\Rand'); | |
/** CONTINUES */ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace My\Custom\Doctrine2\Function; | |
/** | |
* RandFunction ::= "RAND" "(" ")" | |
*/ | |
class Rand extends FunctionNode | |
{ | |
public function parse(\Doctrine\ORM\Query\Parser $parser) | |
{ | |
$parser->match(Lexer::T_IDENTIFIER); | |
$parser->match(Lexer::T_OPEN_PARENTHESIS); | |
$parser->match(Lexer::T_CLOSE_PARENTHESIS); | |
} | |
public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) | |
{ | |
return 'RAND()'; | |
} | |
} |
@jeroensen @dvapelnik IIRC, sorting by RAND()
forces a scan of all matching records, as RAND()
is just a numerical function that returns a random number. If there is a small number of matching records, it should be alright. But if you have millions of matching records and attempt something like ORDER BY RAND() LIMIT 10
, you might be in trouble, as the database will have to scan all these rows, remember all of them along with the number returned by RAND()
for each of them, then extract the few ones with the lowest number (someone correct me if I'm wrong on the details). This is very resource intensive.
There are more efficient ways to select randomly. See for example:
http://jan.kneschke.de/projects/mysql/order-by-rand/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@nocomment17 http://www.doctrine-project.org/2010/03/29/doctrine2-custom-dql-udfs.html