简体   繁体   中英

How to get count for each result in this MySQL query?

I have a table where each row tracks details about when a link was clicked. This query shows the top 5 pages that the user was on when they clicked the link:

$pop_pages = ("SELECT url FROM clicks WHERE link = '$link_id' GROUP BY url ORDER BY url ASC LIMIT 5");

foreach($pop_pages as $page) {

$page_string = $page_string."<li>".$page->url."</li>";

}

This will make a list of the top 5 most frequently clicked URL's. How do I add a count for how many times it was clicked in this query?

Something like:

$page_string = $page_string."<li>".$page->url." (X clicks)</li>";

Try this:

$pop_pages = ("SELECT url, count(url) as c FROM clicks WHERE link = '$link_id' GROUP BY url ORDER BY url ASC LIMIT 5");

foreach($pop_pages as $page) {

$page_string = $page_string."<li>".$page->url." (".$page->c." clicks)</li>";

}

You could do something like this:

$pop_pages = ("SELECT url, COUNT(*) as count FROM clicks WHERE link = '$link_id' GROUP BY url ORDER BY url ASC LIMIT 5");

foreach($pop_pages as $page) {

  $page_string = $page_string."<li>".$page->url." (".$page->count." clicks)</li>";

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM