繁体   English   中英

MYSQL-内部联接3个表

[英]MYSQL - Inner Join 3 Tables

  1. rule_of_exam表字段是id_rule,title_exam,id_class,id_subject,date_posting,id_teacher,信息,状态,时间
  2. score_multichoice表字段是id_score,id_rule,true,false,空,score,id_student
  3. score_essay表字段是id_scoressay,id_rule,id_student,score_essay

我加入了他们的查询

"Select * 
from rule_of_exam 
INNER JOIN score_multichoice ON rule_of_exam.id_rule = score_multichoice.id_rule 
WHERE id_student='$id_student'"

当我加入2张桌子时,它起作用了,但是当我加入3张桌子时,它没有效果。

"Select * from rule_of_exam 
INNER JOIN score_multichoice ON rule_of_exam.id_rule = score_multichoice.id_rule
INNER JOIN score_essay ON rule_of_exam.id_rule = score_essay.id_rule
WHERE id_student='$id_student'"

$id_student来自会话学生。

我期望输出

title_exam | score_essay | score

但它显示

警告:为foreach()提供了无效的参数

问题是id_student出现在多个表中: score_multichoicescore_essay 因此查询不知道选择哪个。 像这样更改查询:

SELECT DISTINCT * FROM rule_of_exam 
INNER JOIN score_multichoice ON rule_of_exam.id_rule = score_multichoice.id_rule
INNER JOIN score_essay ON rule_of_exam.id_rule = score_essay.id_rule
WHERE score_essay.id_student = '$id_student'"

换句话说:告诉MySQL要使用哪个表,它可以工作。 确保您的PHP代码可以处理零个结果行。

如果在两个表中都没有id_student可能会更好。 始终规范化数据库

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM