列出组合在一起的mysql数据并显示每个组的num_rows

时间:2013-09-09 23:34:55

标签: php mysql sql

我有这个SQL代码,它从表中选择行并按类别列

将它们组合在一起
echo '<strong>Categories</strong><br>';
    $sql="SELECT * from tickets where deleted = '' and DAY(datetime) = '04' and MONTH(datetime) = '".date("m")."' and YEAR(datetime) = '".date("Y")."' group by category order by datetime ASC ";
    $rs=mysql_query($sql,$conn);
    while($result=mysql_fetch_array($rs))
    {
        echo $result["category"].' ('.mysql_num_rows($rs).')<br>';
    }

显示行数时,每行显示相同的数字。

如何在每个“类别”旁边显示正确的数字?

2 个答案:

答案 0 :(得分:1)

SELECT *, COUNT(category) AS my_groupcount from tickets

echo $result["category"].' ('.$result["my_groupcount"].')<br>';

答案 1 :(得分:0)

您可能希望进行这样的查询,您可以使用COUNT函数告诉您每个类别分组中的票数。

SELECT  category, COUNT(id) AS NumTickets, MIN(datetime) AS FirstDateTime
FROM tickets 
WHERE deleted = '' AND DAY(datetime) = 4 AND
        MONTH(datetime) = 12 AND YEAR(datetime) = '2012' 
GROUP BY category 
ORDER BY MIN(datetime)