sql查询无法从另一个表中读取(mysql表关系)

时间:2014-05-14 01:07:53

标签: php mysql sql

我的数据库叫做:学生

我的学生表是:有栏目的学生:

STUDENT_ID , STUDENT NAME, ETC.

我的缺席表是:缺席列:

ABSENCE_ID, STUDENT_ID, ETC.

它应该计算每个学生在考虑student_id时有多少缺席记录,并在表格中显示students_id,例如:

+------------+-----------+
| STUDENT ID | ABSENCES  |
+------------+-----------+
| 1          | 3         |
| 2          | 8         |
| 3          | 437       |
+------------+-----------+
  

注意:STUDENT_ID必须从学生表中读取而不是从表中读取表这是问题 !!!!

这是我的两个问题

$result = mysql_query("SELECT student_id, COUNT(*) AS count FROM absences GROUP BY student_id ORDER BY count DESC;");
$result2 = mysql_query("SELECT students.student_id, absences.student_id FROM students INNER JOIN absences ON students.student_id = absences.student_id");

第一个查询工作正常(它计算表上的记录并告诉我有多少缺席)

第二个查询无法正常工作,我希望此查询能够正常工作并为两个查询生成一个查询

我的php代码如下所示:

while($row = mysql_fetch_array($result))
{
    echo "<tr>";
    echo "<td><font size=\"4\" color=\"white\">" . $row['student_id'] . "</font></td>";
    echo "<td><font size=\"4\" color=\"white\">" . $row['count'] . "</font></td>";
    echo "</tr>";
}

3 个答案:

答案 0 :(得分:1)

您可以使用此单个查询来完成任务:

SELECT 
    s.student_id,
    COUNT(a.student_id) as count
FROM students s
LEFT JOIN absences a ON a.student_id = s.student_id
GROUP BY a.student_id
ORDER BY count DESC

这将为您提供所有学生ID的列表以及每个学生ID的完全缺席。无需运行两个查询。如果您需要有关学生的其他数据,只需将其添加到SELECT:s.student_names.student_age等下的字段列表中......

在此处查看此行动:SQL Fiddle

而且,你,don't use mysql_*

答案 1 :(得分:0)

是否使用第二个查询返回每个学生的许多缺勤记录。

$result2 = mysql_query("SELECT students.student_id, count(absences.student_id) as absences FROM students INNER JOIN absences ON students.student_id = absences.student_id GROUP BY absences.student_id");

while($row = mysql_fetch_array($result2))
{
    echo "<tr>";
    echo "<td><font size=\"4\" color=\"white\">" . $row['student_id'] . "</font></td>";
    echo "<td><font size=\"4\" color=\"white\">" . $row['absences'] . "</font></td>";
    echo "</tr>";
}

但是,第一个查询在没有INNER JOIN的情况下的工作方式相同。只有在使用第二个查询返回学生表中存在的字段(例如studant_name)时才可以接受。

mysql _ * 函数自PHP 5.5.0起不推荐使用,不建议用于编写新代码,因为将来会删除它们。相反,应使用mysqliPDO_MySQL扩展名。

答案 2 :(得分:0)

我认为没有办法(有效地)在一个查询中获取所有信息。

// This will get student IDs and their total number of absences
$result = mysql_query("SELECT student_id, COUNT(absence_id) AS total_absences
    FROM absences
    GROUP BY student_id
    ORDER BY count DESC;") or die(mysql_error());

//This will get the details of each student and each absence.
//Add which ever fields you want.
$result2 = mysql_query("SELECT students.student_id, absences.absence_id
    FROM students, absences
    WHERE students.student_id = absences.student_id") or die(mysql_error());

合并两者:

$totalAbsences = array();
while ($row = mysql_fetch_assoc($result)) {
    $totalAbsences[$row['student_id']] = $row['total_absences'];
}

while ($row = mysql_fetch_assoc($result2)) {
    $totalAbsencesForThisStudent = $totalAbsences[$row['student_id']];
    //Make your table here
}

旁注:您应该真正考虑使用mysqli或PDO,因为直接的mysql从PHP5.5开始折旧。