【问题标题】:MYSQL - Inner Join 3 TablesMYSQL - 内连接 3 个表
【发布时间】:2023-03-03 03:34:01
【问题描述】:
  1. rule_of_exam 表 字段为 id_rule、title_exam、id_class、id_subject、date_posting、id_teacher、info、status、time
  2. score_multichoice 表 字段为id_score, id_rule, true, false, empty, 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() 提供的参数无效

【问题讨论】:

  • 你在结果中得到了什么(尝试 var_dump($result) in php

标签: php mysql inner-join


【解决方案1】:

问题在于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 没有出现在两个表中可能会更好。总是normalize your database

【讨论】:

  • @NadyaF.W 我已将DISTINCT 添加到选择中以选择不同的结果。这只有在存在真正的重复项时才会生效。
猜你喜欢
  • 2016-08-31
  • 2013-04-07
  • 1970-01-01
  • 2013-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-20
相关资源
最近更新 更多