需要MySQL的帮助,加入两个查询

时间:2010-02-09 11:55:00

标签: mysql wordpress

我正在运行WordPress,我想编写一个自定义查询,根据一个特定类别显示每月的帖子存档。我使用调试模式了解如何根据所有帖子获取每月存档,选择特定类别。以下是查询:

获取montlhy存档:

SELECT YEAR(post_date) AS `year`, MONTH (post_date) AS `month`, 
  count(ID) as posts FROM wp_posts  
  WHERE post_type = 'post' AND post_status = 'publish' 
  GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC

选择类别:

SELECT t.*, tt.* FROM wp_terms AS t INNER JOIN wp_term_taxonomy
  AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy 
  IN ('category')  AND t.slug = 'blog' ORDER BY t.name ASC

我无法弄清楚如何加入这两个;)任何帮助表示赞赏!

感谢。

更新

还有另一个名为term_relationships的表,因此共有4个表。这是WordPress数据库结构的图像:http://codex.wordpress.org/images/8/83/WP_27_dbsERD.png

无论如何,这就是我所在的地方:

SELECT t.*, tt.*, YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, 
    count(ID) as posts FROM wp_posts, wp_term_relationships AS tr, 
    wp_terms AS t INNER JOIN wp_term_taxonomy AS tt ON t.term_id = tt.term_id 
    WHERE tt.taxonomy IN ('category') AND t.slug = 'blog' 
    AND post_type = 'post' AND post_status = 'publish' 
    AND ID = tr.object_id AND tr.term_taxonomy_id = t.term_id 
    GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC

我知道这不是最好的方式,这就是我需要你帮助的原因;)

感谢。

1 个答案:

答案 0 :(得分:3)

这样的事情如何作为连接的基础和你需要的where子句添加:

    SELECT 
        YEAR(post_date) AS `year`, 
        MONTH (post_date) AS `month`, 
        count(ID) as posts  
    FROM wp_posts 
    INNER JOIN wp_term_relationships wtr ON wp_posts.id = wtr.object_id
    INNER JOIN wp_term_taxonomy wtt ON wtr.term_taxonomy_id = wtt.term_taxonomy_id
    INNER JOIN wp_terms wt ON wtt.term_id = wt.term_id
    WHERE post_type = 'post' AND post_status = 'publish' 
    AND wtt.taxonomy = 'category'
    AND wt.name = 'enter category name here'
    GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC