2014-07-24 3 views
2

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 테이블 교수의 외래 키입니다.

+0

편집 질문. –

+0

당신이 그것에있는 동안 약간의 소스 코드를 던지십시오 – Deryck

+0

Examiners 테이블이 있습니까? –

답변

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); 

@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:[email protected]+1 id, groupID 
    from groups a 
    join (select @row:=0) b) a 
join (
    select @row:[email protected]+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); 
+0

감사. 방금 한 일을 설명해 주시겠습니까? @x : 및 <>는 무엇입니까? 중복 키는 무엇입니까? – hzjw

+0

고마워. 마지막 것. 각 그룹에 대해 서로 다른 심사관을 설정하는 방법은 무엇입니까? 중복이 없습니다. 감사. – hzjw

+0

@ hzjw, 동일한 교수 멤버를 여러 그룹에 할당 할 수 없다는 뜻입니까? – Fabricator

관련 문제