English 中文(简体)
2. 随机记录
原标题:Get random records with Doctrine

我想知道如何从一个集团中随机抽取成员,但我不知道这样做的最佳方式,我认为,由RAND(<>提交的密码不是最好的选择,因为一个集团可能拥有10万多人。 成员进行这种询问可能非常缓慢。

I found this way to make using SQL, but I do not know how to do the same thing in DQL: How can i optimize MySQL s ORDER BY RAND() function?

最佳回答

我不知道从杜古里“高效”向RAND(RAND())穿透任何途径。 在你的情况中,最好的事情可能是首先获得主要钥匙,把这些钥匙捆绑起来,然后在一份国别说明中加以利用。

你还可以增加一个ach层,把第一个 que点的关键(子集)放在一起,特别是如果你有许多记录的话,以避免每次重复对钥匙的质问。

问题回答

To not decrease performances I generally do as follows:

//Retrieve the EntityManager first
$em = $this->getEntityManager();

//Get the number of rows from your table
$rows = $em->createQuery( SELECT COUNT(u.id) FROM AcmeUserBundle:User u )->getSingleScalarResult();

$offset = max(0, rand(0, $rows - $amount - 1));

//Get the first $amount users starting from a random point
$query = $em->createQuery( 
                SELECT DISTINCT u
                FROM AcmeUserBundle:User u )
->setMaxResults($amount)
->setFirstResult($offset);

$result = $query->getResult();  

Of course, the $amount users object you will retrieve are consecutive (i.e. the i-th, (i+1)-th,...,(i+$amount)-th), but usually there is the need of taking one or two entities at random, not the whole list. Hence, I think that this is an effective alternative.

您可以使用你发现的询问,以便通过本地的 s子,有效检索N随机记录,然后通过,使用dql,进行理论查询。

例:

// fetch $randomIds via native sql query using $em->getConnection()->... methods
// or from a memory based cache

$qb = $em->createQueryBuilder( u );

$em->createQuery( 
    SELECT u
    FROM EntityUser
    WHERE   . $qb->expr()->in( u.id , $randomIds) .  
 );

如果你从海滩(如http://redis.io” rel=“nofollow”>redis,可能使用:SRANDMEMBER - first fetch the ids,然后通过向实体发出指示 WHERE IN

你必须保证,你的胎子与数据库相提并论(被删除的胎子从数据库和海滩上清除等等)。





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签