WordPress查询帮助

时间:2011-02-01 19:28:55

标签: mysql wordpress

尝试构建一个有点复杂的WordPress查询。在一个查询中,我试图:

  1. 拉出所有WordPress作者
  2. 只有拥有10个或更多发布帖子的作者(我遇到问题)
  3. 按最新帖子排序作者。
  4. 这是我的原始查询:

    SELECT wp_users.ID, display_name, user_url, user_email, MAX(post_date) as date FROM wp_users, wp_posts WHERE wp_users.ID = wp_posts.post_author AND wp_posts.post_status = 'publish' AND wp_posts.post_type = 'post' GROUP BY display_name ORDER BY date DESC;
    

    此查询会返回所有作者,甚至包含9个或更少发布帖子的作者。

    以下是包含帖子计数的查询:

    SELECT wp_users.ID, display_name, user_url, user_email, MAX(post_date) as date, COUNT(post_date) as post_count FROM wp_users, wp_posts WHERE wp_users.ID = wp_posts.post_author AND wp_posts.post_status = 'publish' AND wp_posts.post_type = 'post' GROUP BY display_name ORDER BY date DESC;
    

    在此查询中,您可以看到我添加了:

    COUNT(post_date) as post_count
    

    它可以很好地回报所有内容。

    只有在我添加此WHERE子句时,查询才会中断

    post_count > 9
    

    我收到此错误消息:

      

    'where子句'中的未知列'post_count'

    知道为什么会这样吗?我的理论:

    1. 不适用于分组
    2. 或MySQL不允许多个AS语句
    3. 如果你能说清楚,我会非常感激。

      感谢。

2 个答案:

答案 0 :(得分:1)

更改查询post_count > 9

的WHERE部分中的条件 在HAVING post_count > 9

之后使用GROUP BY

最终查询将为SELECT wp_users.ID, display_name, user_url, user_email, MAX(post_date) as date, COUNT(post_date) as post_count FROM wp_users, wp_posts WHERE wp_users.ID = wp_posts.post_author AND wp_posts.post_status = 'publish' AND wp_posts.post_type = 'post' GROUP BY display_name HAVING post_count > 9 ORDER BY date DESC;

答案 1 :(得分:1)

您正在寻找“HAVING”操作员。

SELECT wp_users.ID, display_name, user_url, user_email, MAX(post_date) as date, COUNT(post_date) as post_count FROM wp_users, wp_posts WHERE wp_users.ID = wp_posts.post_author AND wp_posts.post_status = 'publish' AND wp_posts.post_type = 'post' GROUP BY display_name HAVING post_count>9 ORDER BY date DESC;