Home > Database > Mysql Tutorial > How to Efficiently Count Unique Website Visitors Per Site in MySQL?

How to Efficiently Count Unique Website Visitors Per Site in MySQL?

Mary-Kate Olsen
Release: 2024-11-27 22:07:14
Original
569 people have browsed it

How to Efficiently Count Unique Website Visitors Per Site in MySQL?

Determining Unique Visitor Count from MySQL Data

To count the unique visitors to a website yesterday using MySQL, you might initially consider a query that groups by the user and timestamp:

SELECT
    DISTINCT `user_id` AS user,
    `site_id` AS site,
    `ts` AS time
FROM
    `cp_visits`
WHERE
    ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
Copy after login

However, relying solely on this distinction can lead to multiple results with the same site_id value. To resolve this, you need to aggregate the results by site_id and count the unique users and visits for each site:

SELECT
    COUNT(DISTINCT user_id) AS countUsers,
    COUNT(site_id) AS countVisits,
    site_id AS site
FROM
    cp_visits
WHERE
    ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
GROUP BY
    site_id
Copy after login

This query will provide a count of unique users (countUsers) and the total number of visits (countVisits) for each unique site_id. By grouping the results by site_id, you ensure that only distinct site logins are counted, avoiding multiple results for the same site.

The above is the detailed content of How to Efficiently Count Unique Website Visitors Per Site in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template