【问题标题】:Set random values from an array into database将数组中的随机值设置到数据库中
【发布时间】:2014-07-24 02:08:39
【问题描述】:

我正在开发一个带有 MYSQL 数据库的 PHP 项目。我有一张学生小组表。每组有一名考官。我想要做的是我想为每组随机设置两名考官。怎么做?

MySQL 代码:

create table groups (
    groupID             int(10)               not null,
    nbStudents          int                   not null,
    avgGPA              DOUBLE                NOT NULL,
    projectName         varchar(50)           not null,
    advisorID           int,                  
    examiner1ID         int,    
    examiner2ID         int,
    adminID             int                   not null,
    primary key (groupID)
);

create table faculty (
    name                varchar(30)         not null,
    facultyID           int(10)                 not null,
    email               varchar(30)           not null,
    mobile              int(15)              not null,            
    primary key (facultyID)
);

examiner1IDexaminer2ID 是来自表 Faculty 的外键。

【问题讨论】:

  • 使用示例数据和所需结果编辑您的问题。
  • 并在你使用的时候输入一些源代码
  • 你有一个 Examiners 表吗?
  • 可以将同一个教员分配到多个组吗?

标签: php mysql database random


【解决方案1】:

这是一种非常复杂的方法。它使用 2 个子查询来挑选教员,并使用 insert .. on duplicate key 来更新考官 ID。

insert into groups
(groupID, examiner1ID, examiner2ID)
select groupID, 
    @x:=(select facultyID from faculty order by rand() limit 1),
    (select facultyID from faculty where facultyID <> @x order by rand() limit 1)
from groups
on duplicate key update examiner1ID=values(examiner1ID), examiner2ID=values(examiner2ID);

@x 是一个user-defined-variable。在这种情况下,它用于存储第一个随机教员。 &lt;&gt; @x 确保我们不会在两个位置中选择相同的教员。

由于groupID 是唯一键,当我们尝试使用现有唯一键插入行时,它将更新现有行而不是插入它。这就是 on duplicate key update 子句的用途。

为每组设置不同的考官:

insert into groups
(groupID, examier1ID, examier2ID)
select a.groupID, max(if(b.id%2, b.facultyID, 0)), max(if(b.id%2, 0, b.facultyID))
from (
    select @row:=@row+1 id, groupID 
    from groups a
    join (select @row:=0) b) a
join (
    select @row:=@row+1 id, facultyID
    from (
        select facultyID
        from faculty a
        order by rand()) a
    join (select @row:=0) b) b on a.id = ceil(b.id/2)
group by a.groupID
on duplicate key update examiner1ID=values(examiner1ID), examiner2ID=values(examiner2ID);

【讨论】:

  • 谢谢。你能解释一下你刚刚做了什么吗?什么是 @x: 和 ?重复键上有什么?
  • 谢谢老兄。最后一件事。如何为每组设置不同的考官?没有重复。谢谢。
  • @hzjw,你的意思是同一个教员不能分配到多个组?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-10
  • 2012-10-20
  • 1970-01-01
  • 2021-03-30
  • 1970-01-01
相关资源
最近更新 更多