MYSQL count of count?

后端 未结 5 2113
执笔经年
执笔经年 2020-12-10 19:36

I have a mysql table like:

id, visitorid, pageid

When a visitor hits the website it stores their visitor id and the page id as a row.

5条回答
  •  再見小時候
    2020-12-10 20:25

    One way to do it is to wrap this query into another one:

    SELECT COUNT(visid) FROM (
        SELECT COUNT(visid) AS cvisid, visid 
          FROM vislog 
      GROUP BY visid 
      HAVING cvisid = 2) AS c
    

    But I think you need to get the histogram of visits: this can be done with PHP (assuming the query is the same as in the question):

    $results = array();
    // query preparation skipped, as it's obviously done by the OP himself
    while ($row = $sth->fetch()) {
      $count = $row['cvisid'];
      if (isset($results[$count])) {
        $results[$count]++;
      }
      else {
        $results[$count] = 1;
      }
    }
    

    Or with MySQL itself:

    SELECT cvisid, 
           COUNT(cvisid) AS cnt 
      FROM (
        SELECT visid,
               COUNT(visid) AS cvisid 
          FROM vislog 
      GROUP BY visid ) AS c
    GROUP BY cvisid
    

提交回复
热议问题