从MySQL表中选择行数百分比的最简单方法?

时间:2010-05-05 06:30:35

标签: php mysql

我有一个包含GET变量的脚本:$_GET['percentage']

我有一个MySQL数据表。

现在假设此表中有100行数据。

在伪代码中:

SELECT data FROM table

现在可以从表中选择$_GET['percentage']个随机数据吗?

例如(再次使用伪代码):

$_GET['percentage'] = 10;
SELECT 10% of data from table order by rand()

如果这是可能的,我怎么能这样做?

4 个答案:

答案 0 :(得分:8)

在MySQL中,在两个查询中执行此操作可能最容易。首先,获取表中的行数:

SELECT COUNT(*) FROM MyTable;

然后准备查询以获取随机行:

SELECT ... FROM MyTable ORDER BY RAND() LIMIT ?;

然后执行准备好的查询并发送计数值除以10。

并非每个问题都需要通过单个查询来解决。


这是一个示例PHP脚本,编辑后使用旧的mysql扩展名。

<?php

// Get the total number of rows in the table.
$sql = "SELECT COUNT(*) FROM Kingdoms";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$rows_in_table = $row[0];

// We only want a portion of the rows, specified by the user
// choice of percentage.  The count we want is therefore equal
// to the total number of rows in the table multiplied by the
// desired percentage.
$percentage = intval($_GET["percentage"]) / 100.0;
$count = intval(round($rows_in_table * $percentage));

// LIMIT makes the query return at most the number of rows specified.
// Sort randomly first (if the table has too many rows this will be slow),
// then return the first $count rows.
$sql = "SELECT * FROM Kingdoms ORDER BY RAND() LIMIT {$count}";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
  print_r($row);
}

PS:将变量插入到SQL表达式时要小心。您应该将变量强制为已知格式 - 在这种情况下为整数值。否则,您将面临创建SQL注入漏洞的风险。

答案 1 :(得分:1)

如果您有自动递增的ID字段,则可以使用

拥有ID_FIELD&lt; = ceil(count(*)* 10/100);

否则存储过程可以为此提供帮助。

答案 2 :(得分:0)

从mytable WHERE RAND()&lt; = 0.5 .....中选择columnvalue将直接导致非常接近50%的记录

答案 3 :(得分:0)

可能是这个事件上升的解决方案

drop event OEAuditEvent;

DELIMITER $$

CREATE EVENT OEAuditEvent
ON SCHEDULE EVERY 1 SECOND
STARTS '2012-09-05 09:00:00'

DO
BEGIN

  DECLARE a CHAR(20);
  DECLARE b,c,d INT;
  DECLARE done INT DEFAULT FALSE;

  IF CURRENT_TIME() = '23:40:00' THEN
begin

 DECLARE cur CURSOR FOR select OE_User,count(OE_User) from RNCM_Status where     date(OE_Date)=CURDATE() group by OE_User; 
 DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; 

 OPEN cur;
 read_loop: LOOP


 FETCH cur INTO a, b;

SET c=ceil((b*5)/100);

IF done THEN

          LEAVE read_loop;
ELSE
          insert into OE_Audit(MDN,CAF,UploadedDate,OEUser,OEDate,UserCount,QCCount,intime) select MDN,CAF,UploadedDate,OE_User,OE_Date,b,c,now() from RNCM_Status where OE_User=a and date(OE_Date)=CURDATE() order by rand() limit c;
    END IF;

 END LOOP;
  CLOSE cur;
 end ;
 END IF;

END $$

DELIMITER ;