连接表以检索数据

时间:2013-08-06 13:58:30

标签: php mysql

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

students_info

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

scores_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

......等所有学生。

3 个答案:

答案 0 :(得分:1)

你有红色吗? http://dev.mysql.com/doc/refman/5.7/en/join.html

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

答案 1 :(得分: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

答案 2 :(得分: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;