我在php中创建一个学校类型的CMS系统以获得更多经验。 我创建了一个schedule.php页面,其中列出了学校类别,例如:
会计 生物学 数学 计算机科学
我想添加一个来自数据库的类别Accounting(2)旁边的数字,因为有2个会计类。例如,计算机科学有10个课程,所以它应该是计算机科学(10)
我的代码只显示主题的名称,而不是教授的课程数量。
这是我的代码:
<?php
include('connect.php');
if(!isset($_GET['id']))
{
?>
<table border="1" width="15%" height="137">
<tr>
<td><?php
//$query1 = mysql_query("SELECT * FROM categories ORDER BY category_name") or die(mysql_error());
$query1 = mysql_query("SELECT CONCAT(a.category_name, ' (', COUNT(b.category_id), ')') AS category
FROM类别a LEFT JOIN类b ON a.id = b.category_id GROUP BY a.id,a.category_name“)或die(mysql_error());
while($row = mysql_fetch_object($query1))
{
print "<a href='schedule.php?id=" . $row->id . "'>" . $row->category . "</a><br/>";
} ?></td>
</tr>
<?php
}
//if you click on the subject
else if(isset($_GET['id']))
{
$category = $_GET['id'];
$sql = "SELECT * FROM classes WHERE category_id = " . $category;
$query2 = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_object($query2))
{
?>
<center><h3><?php echo $row->class_name . '-' . $row->units; ?> </h3></center>
<table border ="0" wdith="100%">
<tr>
<td>
<strong>Description: </strong>
<?php echo $row->class_description; ?>
</tr>
</td>
</table>
<br/>
<table border="1" width="44%">
<tr>
<td width="60"><b>Ticket</b> </td>
<td width="123"><b>Days</b></td>
<td width="120"><b>Hours</b></td>
<td width="64"><b>Room</b></td>
<td><b>Instructor</b></td>
</tr>
<tr>
<td width="60"> <?php echo $row->ticket; ?> </td>
<td width="123"><?php echo $row->days; ?></td>
<td width="120"><?php echo $row->start_hours . $row->time_format . '-' . $row->end_hours . $row->time_format2 ; ?> </td>
<td width="64"> <?php echo $row->room_number; ?></td>
<td><?php echo $row->instructor_name; ?></td>
</tr>
}//end while
}//end else if
&GT;
由于
答案 0 :(得分:1)
最好使用带有join和group by子句的查询。它可能看起来像这样:
SELECT
ca.*,
COUNT(cl.id) AS class_count
FROM
categories ca
LEFT JOIN classes cl ON cl.category_id = ca.id
GROUP BY ca.id
答案 1 :(得分:1)
假设您的架构符合以下几行:
+---------------+ +--------------------+
| categories | | classes |
+---------------+ +--------------------+
| ID | | id |
| category_name | | category_id |
| etc.. | | etc... |
+---------------+ +--------------------+
classes.category_id
是引用categories.id
的外键,有一个非常简单的解决方案:
SELECT a.ID, CONCAT(a.category_name, ' (', COUNT(b.category_id), ')') AS category
FROM categories a
LEFT JOIN classes b ON a.ID = b.category_id
GROUP BY a.ID, a.category_name
这会将类的数量连接到每个类别。实施例
Biology (4)
Computer Science (10)
etc...
您可以在PHP中简单地引用查询的category
列。
while($row = mysql_fetch_object($query1))
{
print "<a href='schedule.php?id=" . $row->ID . "'>" . $row->category . "</a><br/>";
}