gpt4 book ai didi

php - 将数组中的随机值设置到数据库中

转载 作者:搜寻专家 更新时间:2023-10-30 20:39:43 24 4
gpt4 key购买 nike

我正在使用 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 的外键。

最佳答案

这是一个非常复杂的方法。它使用 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);

@xuser-defined-variable .在这种情况下,它用于存储第一个随机教员。 <> @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);

关于php - 将数组中的随机值设置到数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24924015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com