简体   繁体   English

使用COUNT(PHP MySQL)累加行号并显示总计

[英]Adding up row number and displaying total using COUNT (PHP MySQL)

I'm attempting to run a query that adds up the total number of subjects in a class. 我正在尝试运行一个查询,该查询将一个类中的学科总数加起来。 A class has many subjects. 一堂课有很多科目。 There is a 'teachersclasses' table between teachers (the user table) and classes. 在教师(用户表)和班级之间有一个“教师班级”表。 The principles sounds pretty simple but I'm having some trouble in getting my page to display the number of subjects for each class (directly associated with the teacher) 原理听起来很简单,但在让我的页面显示每个班级的科目数(与老师直接相关)时遇到了一些麻烦

This is what I have so far, trying to make use of the COUNT with a nested SELECT: 到目前为止,这就是我尝试使用带有嵌套SELECT的COUNT的原因:

SELECT (SELECT count(*) FROM subjects WHERE subjects.classid = class.classid) AS total_subjects, class.classname, class.classid 

FROM class 从类

Then I am calling up 'num_subjects' to present the total within a while loop: 然后我调用'num_subjects'来在while循环中显示总数:

            <?php echo $row['total_subjects']?>

From the above, I am receiving the total subjects for a class, but within the same table row (for one class) and my other while loop doesnt run anymore, which returns all of the classes associated with a teacher :( ... Bit of a mess now! 从上面的内容中,我正在接收一门课程的总科目,但是在同一表行(对于一个课程)内,而我的另一个while循环不再运行,这将返回与教师相关的所有课程:( ...位一团糟吧!

I know to return the classes for a particular teacher, I can do an additional WHERE clause on the session of 'teacherid' but I think my query is getting too complicated for me that errors are popping up everywhere. 我知道要为特定的老师返回课程,我可以在“ teacherid”的会话上添加一个WHERE子句,但我认为我的查询对我来说太复杂了,到处都会出现错误。 Anyone have a quick fix for this! 任何人都可以快速解决此问题! Thanks very much 非常感谢

Your query is probably not optimal. 您的查询可能不是最佳的。 It might be a good idea to rewrite it as a join: 将其重写为联接可能是一个好主意:

SELECT
    total_subjects,
    class.classname,
    class.classid 
FROM class
JOIN (
    SELECT classid, count(*) AS total_subjects
    FROM subjects
    GROUP BY classid
) AS T1
ON T1.classid = class.classid

As for your problem, you don't need two loops. 至于您的问题,您不需要两个循环。 This is a single result set with three columns, as my rewrite clearly shows. 正如我的重写清楚显示的那样,这是一个包含三列的单个结果集。 You only need one loop to read all the results. 您只需要一个循环即可读取所有结果。

SELECT count(*) FROM subjects GROUP BY subjects.classid

You don't need the "subselect", you can just do a JOIN and count() 您不需要“ subselect”,只需执行JOIN和count()

SELECT 
  class.*, 
  count(subjects.*) AS total_subjects 
FROM 
  class 
  LEFT JOIN subjects ON class.classid = subjects.classid
WHERE 
  class.teacherid = ?
GROUP BY
  class.classid

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM