我有主题表包含主题详细信息,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>";
}
答案 0 :(得分: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
您还可以在print_r
中使用while
作为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";