简体   繁体   中英

Need help in connecting two tables without exactly the same info in the joined tables

I have two tables: articles and log

the articles table has these columns

  • title represents whole name of article
  • slug represents shorter version of the name

example

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 values
  • id represents the user id that has read that article

I 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

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.

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;  

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