比较数据库中不同表的2列

时间:2018-08-14 12:59:17

标签: mysql database

我正在尝试比较2个不同表(EXERCISES,ANSWERS)中的2列(难度,student_student),并在表ANSWERS中创建一个新列,将两个表与布尔值进行比较(是或否)。如果用户更改了锻炼难度,则该单元格将为“是”,如果尚未更改,则该单元格将为“否”。

这是我的2张桌子。我想比较表EXERCISES的“难度”和表ANSWERS的“ difficulty_student”,并将其存储在表ANSWERS的“ difficulty_chage”中。

CREATE TABLE exercises (
    exercise_id INT,
    difficulty INT
    PRIMARY KEY(exercise_id)
);

CREATE TABLE answers(
    exercise_id_fk INT,
    student_id INT,
    difficulty_change BOOLEAN,
    difficulty_student INT,
    choice_answer INT,
    FOREIGN KEY(exercise_id_fk) REFERENCES exercises(exercise_id)
);

这是我尝试过的方法,但是没有用,您能帮我吗?

SELECT exercises.difficulty, answers.difficulty_student, 
       IF(difficulty = difficulty_student, NO) as difficulty_change
FROM answers
ELSE 'YES' as difficulty_change FROM answers

这就是我想要的:

enter image description here

2 个答案:

答案 0 :(得分:2)

在您的场所中,没有桌子用户,而是锻炼并回答
您可以加入表格(假设基于exercise_id的关系)

SELECT e.difficulty, a.difficulty_student, 
case when e.difficulty = a.difficulty_student then 'NO' else 'YES' 
         END  as difficulty_change
FROM exercises e 
INNER JOIN answer a  on e.exercise_id=a.exercise_id_fk

要更改表答案中的column_change列,您应该使用一个已更新的...,但是您在cability_change列中具有整数,因此您可以使用数字结果进行查询,例如:

UPDATE answer a 
INNER JOIN exercises e  on e.exercise_id=a.exercise_id_fk
set a.difficulty_change =   case when e.difficulty = a.difficulty_student then 0 else 1 END
where e.exercise_id=a.exercise_id_fk

或您必须将comfort_change的数据类型更改为varchar(3)并使用

UPDATE answer a 
INNER JOIN exercises e  on e.exercise_id=a.exercise_id_fk 
set a.difficulty_change = case 
     when e.difficulty = a.difficulty_student then 'NO' else 'YES' END
where e.exercise_id=a.exercise_id_fk

答案 1 :(得分:2)

如果要将更改保留在数据库上,则可以使用更新语句:

update answers 
inner join exercises on answers.exercise_id_fk = exercises.exercise_id 
set answers.difficulty_change = 'YES' 
where answers.difficulty_student != exercises.difficulty;

注意:对于 answers 表, difficulty_change 列应为VARCHAR(3),以使用值“ YES”或“ NO”。我假设您的 answers 表默认情况下在 difficulty_change 列上的值为“ NO”。

这是我用来测试查询的架构和数据:

CREATE TABLE exercises (
    exercise_id INT,
    difficulty INT,
    PRIMARY KEY(exercise_id)
);

CREATE TABLE answers(
    exercise_id_fk INT,
    student_id INT,
    difficulty_change VARCHAR(3),
    difficulty_student INT,
    choice_answer INT,
    FOREIGN KEY(exercise_id_fk) REFERENCES exercises(exercise_id)
);

insert into exercises values (1,1);
insert into exercises values (2,2);
insert into exercises values (3,3);
insert into exercises values (4,4);
insert into exercises values (5,5);

insert into answers values (1,1,'NO',1,1);
insert into answers values (2,1,'NO',2,1);
insert into answers values (3,1,'NO',3,1);
insert into answers values (4,1,'NO',5,1);
insert into answers values (5,1,'NO',4,1);