【问题标题】:SQL Count from table and display individual counts in while display php表中的 SQL 计数并在显示 php 时显示单个计数
【发布时间】:2013-01-31 09:33:53
【问题描述】:

您好,我对数据库相当陌生,我正在尝试从具有相关表的数据库中计算数据。我正在尝试计算与另一个表中的记录相关的条目,然后在相关记录旁边显示该计数。目前我只是获取条目的完整计数,并在所有记录旁边显示完整计数。![在此处输入图像描述][1]

//Individual Stores Total
$query_stores = "SELECT COUNT(stores.name) AS num FROM entries,stores WHERE stores.id = entries.store_id AND valid=1";
$results_stores = mysql_query($query_stores);
$rows_stores = mysql_fetch_array($results_stores);


echo "<tr>";
      echo "<td >" . $info['name'] . "</td>";  
      echo "<td>" . $info['code'] . "</td>";
      echo "<td bgcolor='#00B050'>" . $rows_stores['num'] . "</td>";
      echo "</tr>";

【问题讨论】:

    标签: php sql count


    【解决方案1】:

    在您的查询中试试这个:

    SELECT COUNT(stores.id) AS num, stores.name, stores.id as code
    FROM entries,stores 
    WHERE stores.id = entries.store_id AND valid=1
    GROUP BY stores.id
    

    【讨论】:

    • 感谢您的建议...我已经尝试了您的所有建议。 @RainHeart > 我试过你的查询,它似乎给出了最好的响应,尽管它仍然用计数填充整个数组,而不仅仅是与数据相关的字段。你还有什么我可以尝试的技巧吗?
    • 我不明白It is still populating the whole array with the count instead of just the fields that are related with the data。请告诉我您从查询中得到什么以及您想要得到什么(在第一条消息中),我们将能够找到解决方案
    【解决方案2】:

    我认为您的查询是错误的。试试这样的:

    SELECT e.id, count(s.name) FROM entries as e JOIN stores as s ON (e.store_id=s.id)
          WHERE e.valid=true
          GROUP BY e.id
    

    【讨论】:

    • 查询没问题。在代码中实现之前,我测试了 mysql 工作台。我只是不知道如何根据需要显示数据
    【解决方案3】:

    你必须加入两个表并使用 group by

    $query_stores = "SELECT COUNT(stores.name) AS num FROM entries Inner Join stores ON   
                     stores.id = entries.store_id WHERE valid=1 GROUP BY stores.name";
    $results_stores = mysql_query($query_stores);
    $rows_stores = mysql_fetch_array($results_stores);
    

    【讨论】:

    • > 我已经尝试加入表格,但是在使用 while 条件填充数据时,显示将是列中的完整计数,而不是单个相关的整体。另请参阅 RainHearts 查询...
    猜你喜欢
    • 2014-08-27
    • 1970-01-01
    • 2014-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-19
    • 2015-06-25
    相关资源
    最近更新 更多