Wordpress - 按天获取帖子和评论的数量

时间:2011-02-11 21:46:57

标签: php mysql wordpress join

我需要对Wordpress博客中的活动进行加权。比如,有一天有3个帖子和10个评论,一个帖子的分数是10,只有1个评论,然后说总共有40个点。但是,可能会有一些日子没有发布活动或没有评论活动。

我的第一个想法是从帖子到评论表的简单LEFT JOIN。但是,这将排除没有帖子的日子。我不是MySQL大师,但我一直在研究,似乎解决这个的最好方法是使用FULL OUTER JOINexplained by Jeff Atwood),但MySQL不支持这个!

然后,实际上有a workaround,但它不适合我。似乎RIGHT OUTER JOIN没有返回我需要的东西 这是LEFT一个,效果很好。

SELECT
    DISTINCT DATE(post_date) AS day,
    COUNT(ID) AS post_total,
    COUNT(comment_ID) as comment_total,
    (COUNT(ID)*10 + COUNT(comment_ID)*1) AS total
FROM wp_posts
    LEFT OUTER JOIN wp_comments ON
        DATE(post_date) = DATE(comment_date)
GROUP BY day ORDER BY total DESC

RIGHT一个错误。

SELECT
    DISTINCT DATE(post_date) AS day,
    COUNT(ID) AS post_total,
    COUNT(comment_ID) as comment_total,
    (COUNT(ID)*10 + COUNT(comment_ID)*1) AS total
FROM wp_posts
    RIGHT OUTER JOIN wp_comments ON
        DATE(post_date) = DATE(comment_date)
GROUP BY day ORDER BY total DESC

因此,UNION解决方法毫无用处。

我做错了什么?有更简单的方法吗?

感谢。

注意:您必须在不同日期添加一些帖子和评论。

1 个答案:

答案 0 :(得分:0)

我认为这不是你能写的最好的查询,但似乎有用

CREATE VIEW commentsCount (date, counter) AS
SELECT
    DISTINCT DATE(comment_date) AS date,
    IFNULL(COUNT(comment_ID),0) AS total
FROM wp_comments
GROUP BY date ORDER BY total DESC

CREATE VIEW postsCount (date, counter) AS
SELECT
    DISTINCT DATE(post_date) AS date,
    IFNULL(COUNT(ID),0) AS total
FROM wp_posts
GROUP BY date ORDER BY total DESC

SELECT
    postsCount.date,
    IFNULL(postsCount.counter,0),
    IFNULL(commentsCount.counter,0),
    (IFNULL(postsCount.counter,0)*10 + IFNULL(commentsCount.counter, 0))
FROM commentsCount RIGHT JOIN postsCount 
    ON DATE(postsCount.date) = DATE(commentsCount.date)
GROUP BY postsCount.date
union
SELECT
    commentsCount.date,
    IFNULL(postsCount.counter,0),
    IFNULL(commentsCount.counter,0),
    (IFNULL(postsCount.counter,0)*10 + IFNULL(commentsCount.counter, 0))
FROM commentsCount LEFT JOIN postsCount 
    ON DATE(postsCount.date) = DATE(commentsCount.date)
GROUP BY commentsCount.date