S
S
Sergey2019-10-25 10:13:33
MySQL
Sergey, 2019-10-25 10:13:33

Sorting by views per day / week / month - how to build a query?

Hi guys.
You need to sort Wordpress posts by views for 24 hours, 7 days, 30 days.
Given:

  • WP Post Table
  • wp_post_views table with two fields: ID (post ID) and time (stores the date and time of the view)

Actually, you need to build an SQL query that will sort the posts from the wp_posts table by the number of rows with the post ID in the wp_post_views table for the required period.
Any ideas how this can be done? Tried to do through JOIN, GROUP BY and COUNT. Nothing worked for me ... In SQL, I'm a complete layman.
Thanks in advance :)
Found this solution:
SELECT `ID`, `post_title` FROM `wp_posts` AS t1
INNER JOIN `wp_post_views` AS t2 USING(`ID`)
WHERE t2.time >= CURDATE() - INTERVAL 30 DAY /* или 1 DAY, или 7 DAY*/
GROUP BY `ID`
ORDER BY COUNT(t2.ID) DESC 
LIMIT 10

Execution result:
5db2ab89712a3064959787.png
It seems to work, but it's not certain ... Mb will come in handy for someone :)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey c0re, 2019-10-25
@Kianl

Something like this, if I'm not mistaken:

SELECT
      `ID`
    , `post_title`
    , pv30.cnt_month
    , COALESCE(pv7.cnt_week, 0) cnt_week
    , COALESCE(pv1.cnt_day, 0) cnt_day
  FROM `wp_posts` AS p
  INNER JOIN (
    SELECT id, count(id) cnt_month
      FROM `wp_post_views` pv
      WHERE pv.time >= CURDATE() - INTERVAL 30 DAY
      GROUP BY pv.id
    ) AS pv30
    ON pv30.id = p.id
  LEFT JOIN (
    SELECT id, count(id) cnt_week
      FROM `wp_post_views` pv
      WHERE pv.time >= CURDATE() - INTERVAL 7 DAY
      GROUP BY pv.id
    ) AS pv7
    ON pv7.id = p.id
  LEFT JOIN (
    SELECT id, count(id) cnt_day
      FROM `wp_post_views` pv
      WHERE pv.time >= CURDATE() - INTERVAL 1 DAY
      GROUP BY pv.id
    ) AS pv1
    ON pv1.id = p.id
  ORDER BY pv30.cnt_month DESC, pv7.cnt_week DESC, pv1.cnt_day DESC
  LIMIT 10;

T
tisprk, 2019-10-25
@tisprk

There is nowhere to check. I would venture to guess:
--24 hours
select * from wp_posts wp
inner join wp_post_views wv on wp.id = wv.id
where time > DATE_SUB(CURDATE(), INTERVAL 24 HOUR);
-- 7 days
select * from wp_posts wp
inner join wp_post_views wv on wp.id = wv.id
where time > DATE_SUB(CURDATE(), INTERVAL 168 HOUR);
-- 30 days
select * from wp_posts wp
inner join wp_post_views wv on wp.id = wv.id
where time > DATE_SUB(CURDATE(), INTERVAL 720 HOUR);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question