SQL查询不能从另一个表中读取(mysql表关系)


sql query cannot read from another table (mysql table realations)

我的数据库叫:students

我的学生表是:学生,列:

STUDENT_ID , STUDENT NAME, ETC.

我的缺席表是:缺席与列:

ABSENCE_ID, STUDENT_ID, ETC.

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

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

注意:学生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>";
}

您可以使用这个查询来完成您的任务:

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和每个学生缺勤总数的列表。不需要运行两个查询。如果您需要有关学生的其他数据,只需将其添加到SELECT: s.student_name, s.student_age等下的字段列表中…

SQL Fiddle

, 不要使用mysql_ *

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

$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的情况下以相同的方式工作。只有在使用第二个查询返回student表中存在的字段时才可以接受,例如studant_name

mysql_* functions在PHP 5.5.0中已弃用,不建议编写新代码,因为它将在将来被删除。相反,应该使用mysqli或PDO_MySQL扩展名。

我不认为有任何方法可以(有效地)在一次查询中获得所有的信息。

// 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中贬值了。