Every time somebody visits a blog article on my site, I record this in a table [blog_article_hits]. Each visit has one row. I now want to display a list of trending articles in the last 14 days, showing the article title and the amount of hits it’s received or a percentage.
Example:
This is a blog article 1,0732
This is another article 930
My Attempt:
SELECT
tre.article_id, COUNT(*) AS total_hits, art.title, art.description,
pho.photo_id
FROM blog_article_stats tre
LEFT JOIN blog_articles AS art ON tre.article_id = art.article_id
LEFT JOIN blog_photos AS pho ON art.article_id = pho.article_id
WHERE tre.d_time BETWEEN DATE_SUB(Now(), INTERVAL 14 DAY) AND Now()
AND pho.status = 'Published' AND art.status = 'Published'
GROUP BY tre.article_id
ORDER BY total_hits DESC LIMIT 5
It’s very close but not quite right. The most popular articles are listed in the correct order but the count next to each title is incorrect. It’s actually showing how many photos there are for each article, not how many times it’s been visited. I thought by having the GROUP BY would help, I even tried adding a secondary GROUP clause on [pho.article_id] but that didn’t help.
I’m selecting [pho.photo_id] and joining [pho.blog_photos], purely because I want to show one photo next to each listed result.
Can anybody advise me on how to resolve this issue?
Many thanks in adv.
Change the count to:
where
PKis the primary key of that table.