在单个查询中为每个类别选择n个帖子

时间:2011-11-30 04:06:17

标签: php mysql wordpress

在我的主页中,我会显示不同类别的不同帖子。 我目前的实现是多次调用query_posts(每个类别一次)

如何使用一个查询来提取数据?

我的尝试

1 - 这个方法有效(忽略丑陋很长的sql,我有很多类别......)
感谢帖子:http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/

( SELECT * 
  FROM `wp_posts` p,`wp_term_relationships` rel 
  WHERE rel.object_id = p.ID 
   AND rel.term_taxonomy_id = '3' 
  ORDER BY p.post_date DESC 
  LIMIT 2)
UNION ALL 
( SELECT * 
  FROM `wp_posts` p,`wp_term_relationships` rel 
  WHERE rel.object_id = p.ID 
    AND rel.term_taxonomy_id = '4' 
  ORDER BY p.post_date DESC 
  LIMIT 2)

1 个答案:

答案 0 :(得分:1)

SELECT i.* 
FROM wp_term_relationships rel
INNER JOIN ( 
  SELECT p.*, rel2.* 
  FROM wp_posts p
  INNER JOIN wp_term_relationships rel2
          ON (rel2.object_id = p.ID) 
  WHERE rel2.term_taxonomy_id = rel.term_taxonomy_id
  ORDER BY p.post_date DESC 
  LIMIT 2 OFFSET 0 ) i ON (i.object_id = rel.object_id)
WHERE rel.term_taxonomy_id IN ('3','4')
ORDER BY i.term_taxonomy_id ASC, i.post_date DESC