2

我有三个链接在一起的表。我想做的是为一个班级的所有学生生成一张成绩单。

学生信息

name      sex age students_ID
--------- --- --- -----------
Kinsley   M    12           1
Michael   m    12           2
Rhianna   f    22           3

score_panel

1stCA 2ndCA exam students_ID subjectID
----- ----- ---- ----------- ---------
   23    15   42           1         1
   10    12    7           1         2
   43    15   62           1         3
   10    12   27           2         1
   10    12   57           2         2
   23    15   12           2         3
   11    12   27           3         1
   04    12   57           3         2
   13    25   12           3         3

主题

subjectname subjectID
----------- ---------
english             1
maths               2
biology             3

我希望我的结果看起来像这样:

NAME KINSLEY
SEX M
AGE 12

和成绩单跟随

subject   1stCA 2ndCA EXAM
--------- ----- ----- ----
english      23    15   42
maths        10    12    7
Biology      43    15   62

...等等所有学生

只检索一门科目和分数,而不是全部

<?php
include("connect.php");

$generate="SELECT students_info.name, subject.subjectname, scores_panel.1stCA, scores_panel.2ndCA, scores_panel.EXAM
FROM
students_info
LEFT JOIN
scores_panel
ON students_info.students_ID=scores_panel.students_ID
LEFT JOIN
subject
ON
subject.subjectID=scores_panel.subjectID ";

$fetch=mysql_query($generate);
while($row=mysql_fetch_array($fetch)or die(mysql_error()))
{
?>
**NAME:** 
<?PHP echo $row['name']; ?>
subject 1stCA 2ndCA EXAM
----------
<?PHP echo $row['subjectname']; ?>
<?PHP echo $row['1stCA']; ?>     
<?PHP echo $row['2ndCA']; ?>   
<?PHP echo $row['EXAM']; ?>

THIS IS YOUR REPORT CARD 
<?PHP } ?>

它有效,但只为每个学生显示一个主题,而不是像这样:

  NAME KINSLEY
    SEX M
    AGE 12

和成绩单跟随

subject   1stCA 2ndCA EXAM
--------- ----- ----- ----
english      23    15   42
maths        10    12    7
Biology      43    15   62


  NAME Rhianna 
    SEX F
    AGE 22

和成绩单跟随

subject   1stCA 2ndCA EXAM
--------- ----- ----- ----
english      11    12   27
maths        04    12    57
Biology      13    25   12

...等等所有学生。

4

3 回答 3

1

简单的 MySQL left join应该可以解决这个问题:

SELECT
st.name, st.sex, st.age,
sub.subjectname,
sc.1stCA, sc.2ndCA, sc.exam
FROM scores_panel AS sc
LEFT JOIN subject AS sub ON sub.subjectID = sc.subjectID
LEFT JOIN students_info AS st ON st.students_ID = sc.students_ID
于 2013-08-06T14:14:34.097 回答
1

这是SQLFiddle

查询是

SELECT T1.NAME, T1.SEX, T1.AGE, T2.EXAM, T3.SUBNAME, T2.1CA, T2.2CA
   FROM TAB1 AS T1 LEFT JOIN TAB2 AS T2 ON T1.STUDENT_ID = T2.STUDENT_ID
      LEFT JOIN TAB3 AS T3 ON T2.SUBJ_ID = T3.SUBID;
于 2013-08-06T14:20:10.780 回答
1

你红过这个吗? http://dev.mysql.com/doc/refman/5.7/en/join.html

如果您已经了解表连接,那么您必须准确/向我们展示您的问题到底是什么(意味着您的代码的当前状态是什么)

于 2013-08-06T14:09:56.663 回答