Reputation: 123
I have two tables: articles
and log
the articles table has these columns
title
represents whole name of articleslug
represents shorter version of the nameexample
title | slug
-----------------------------------------|----------------------------
cats are cute and wonderfully adorable | cats-are-cute
log
table has columns:
path | id
------------------------------|--------
/article/cats-are-cute | 123
path
represents the slug but with a start of '/article/'
and also has some empty valuesid
represents the user id that has read that articleI need a query to find What are the most popular three articles of all time
I tried this
select articles.title, count(log.id) as views
from articles
right join log on log.path like concat('/article/',articles.slug)
group by articles.title
order by views desc limit 3;
it doesn't show correct values.
both answers below are correct, but the one i chose takes less processing time
Upvotes: 1
Views: 62
Reputation: 3357
Try this one
SELECT articles.title, tmp.views
FROM (SELECT path, Count(path) AS views
FROM log
GROUP BY path) tmp
INNER JOIN articles ON tmp.path = Concat('/article/', articles.slug)
ORDER BY tmp.views DESC
LIMIT 3;
Upvotes: 1
Reputation: 521914
It sounds like you want to check if the slug
column of the articles
table is contained within the path
of the log
table. We can try using a POSIX regex in Postgres to handle that:
SELECT
a.title,
COUNT(l.id) AS views
FROM articles a
LEFT JOIN log l
ON l.path ~ CONCAT('.*\y', a.slug, '\y.*')
GROUP BY
a.title
ORDER BY
views DESC
LIMIT 3;
This would match any path which contains, as an exact path component, the slug from the corresponding article.
Upvotes: 1