dtbiszu7724 2014-12-02 20:35
浏览 83
已采纳

通过使用php将随机数插入mysql表,将条目分组为5个随机组

I have a MySQL table with columns including id, names of people and a random number. What I would like to do is every week, collect the names into random groups of 5 each. It's for 5 aside football tournaments and it's getting too big to do it by hand now and I'd like it to be automatic.

The way I think it'll work will be to get the num_rows, divide by 5 to get the total number of groups ($divide). Then make a loop where 5 rows are selected at random and a random number between 1 and $divide is given to them. It's got to change every week so it can't be a one off task. I'd also like it to accommodate situations where the num_rows doesn't exactly divide by 5 and creates a last group of the remaining number.

This is as far as I've got -

$num_rows = mysql_num_rows($data);

$divide = $num_rows / 5;

$rannum = RAND (1, $divide);

$sql = mysql_query("UPDATE allpeep SET rannumber = $rannum")
or die(mysql_error());

but as you may have guessed, this just inserts the same random number into all the rows. I think this requires a while loop, but I can't quite work out how it'll work.

  • 写回答

2条回答 默认 最新

  • dousi6405 2014-12-02 20:50
    关注
    SELECT * FROM TABLE ORDER BY RAND() LIMIT 5 
    

    But this still isn't going to protect from duplicate if multiple queries are made, so ...

    SELECT * FROM TABLE ORDER BY RAND()
    

    Get the whole set, then parse into 5's in your server script. I'm assuming you want these static until next week, so for each 5 set update the sql server telling them what 'group' they are in this week.

    In the alternative, you could use the former syntax if you use a seed for the rand() function. Using the year/week of year combination will give you a reproducable rand sequence

    SELECT * FROM TABLE ORDER BY RAND(YEARWEEK(CURDATE()))
    

    Then you avoid having to update anything on the server, and only have to output the results

    $result = mysql_query("SELECT * FROM {tablename} ORDER BY RAND(YEARWEEK(CURDATE()))")
    or die(mysql_error());
    
    $group = 1;
    $row = true;
    while ($row) {
      echo "Group $group";
      for ($i=0; $group++, $i<5 && $row=mysql_fetch_assoc($result); $i++) {
        // output current row
        echo "team $row['team']";
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧