【问题标题】:MYSQL select from table and count from anotherMYSQL 从表中选择并从另一个表中计数
【发布时间】:2017-11-24 10:57:59
【问题描述】:

我有 subject 表包含科目详细信息,而 subject_student 表包含学生选择的科目。我想选择超过 2 名学生选择的所有科目详细信息,并获取超过 2 名学生选择的每个科目的学生人数。

科目表

------------------------------
ID  | Name          | units 
------------------------------
1   | web           | 1
2   | programming   | 1
3   | java          | 1
4   | QA            | 1
------------------------------ 

student_subject 表

主题表

------------------------------
student_id | subject_id | status 
------------------------------
1          | 1          | current
1          | 2          | current
2          | 1          | current
2          | 3          | current
3          | 1          | current
3          | 3          | current
4          | 1          | current
5          | 5          | current
------------------------------   

所以这里的结果必须选择科目表的第一行和选择网络科目的学生数 4 这是查询:

$query= "
SELECT s.sub_ID
     , s.Name
     , s.units
     , count(st.subject_id) as cc 
  from subjects as s 
  LEFT 
  JOIN students_subject as st
    ON s.ID = st.subject_id 
 GROUP 
    BY st.subject_id  
Having count(st.subject_id)>2)
";

当我运行代码时,它给了我这个错误: 注意:试图获取非对象的属性

这里是 PHP 代码:

global $con,$users;
    $query= "SELECT s.sub_ID,s.Name, s.units,s.dept, count(st.subject_id)as cc from subjects as s LEFT JOIN students_subject as st
    ON s.ID=st.subject_id GROUP BY st.subject_id  Having count(st.subject_id)>2)";
    //$query="SELECT * FROM subjects;";
    $result=mysqli_query($con,$query);
    if ( $result->num_rows == 0 ) // User doesn't exist
        echo "Subjects doesn't exist!";
    else { echo "
        <tr>
            <th>Subjects ID</th>
            <th>Title</th>
            <th>Units</th>
            <th>Department</th>
            <th>Check</th>
        </tr>";

       $r=0;
      while($row = mysqli_fetch_array($result))
        {


            echo "<tr>";
            echo "<td>" . $row['sub_ID'] . "</td>";
            echo "<td>" . $row['Name'] . "</td>";
            echo "<td>" . $row['units'] . "</td>";
            echo "<td>" . $row['cc'] . "</td>";
        }

【问题讨论】:

标签: php mysql


【解决方案1】:

检查您的查询以获取表和列的名称Subjects(ID,Name,units), students_subject(student_id,subject_id,status)

SELECT
  sb.id AS sub_ID, -- !!!
  sb.Name,
  sb.units,
  COUNT(st.student_id) AS cc
FROM Subjects sb
JOIN students_subject st ON st.subject_id=sb.id
GROUP BY sb.id,sb.name,sb.units
HAVING COUNT(st.student_id)>2

您还可以在while 中使用print_r 来作为mysqli_fetch_array 返回的测试名称

while($row = mysqli_fetch_array($result))
{
  print_r($row);
  ...

这里不需要括号)

$query= "...  Having count(st.subject_id)>2)"; // <--

尝试删除它

$query= "...  Having count(st.subject_id)>2";

【讨论】:

    猜你喜欢
    • 2013-07-17
    • 2014-06-12
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-23
    • 1970-01-01
    • 2021-12-30
    相关资源
    最近更新 更多