wordpress:查询从多个特定类别中选择最后一个帖子

时间:2014-03-14 14:29:04

标签: sql wordpress categories

我需要从3个不同类别中选择最后一篇文章。 直到现在,我有一个这样的查询:

select ID, t.term_id term_id, post_title, post_content, t.slug as category 
from e_posts p
inner join e_term_relationships tr on p.ID = tr.`object_id`
inner join e_term_taxonomy tt on tr.term_taxonomy_id = tt.term_taxonomy_id
inner join e_terms t on t.term_id = tt.term_id 
where tt.taxonomy = "category" and t.term_id IN(4,670,158)

结果是这样的:

enter image description here

如果我尝试按term_id分组,我会收到每个词(类别)的第一篇帖子。即使我按日期订购。我能做什么?我想这不是太难但不能弄明白......

1 个答案:

答案 0 :(得分:1)

您的问题与greatest-n-per-group代码相关(请查看)您需要获取符合条件的最新帖子。所以这是您的解决方案:使用p.ID = tr. object_id AND p.post_date = tr.post_date获取其最大日期自我加入的帖子,以便获取最近的帖子

SELECT DISTINCT
  p.ID, 
  t.term_id term_id, 
  p.post_title, 
  p.post_content, 
  t.slug AS category 
FROM 
  e_posts p
INNER JOIN
  (SELECT 
     etr.*,
     pp.ID,
     MAX(pp.post_date) post_date 
   FROM 
     e_posts pp 
INNER JOIN 
  e_term_relationships etr 
ON 
  pp.ID = etr .`object_id`  
GROUP BY 
  pp.ID,etr.term_taxonomy_id) tr  
ON 
  (p.ID = tr.`object_id` AND p.post_date = tr.post_date)
INNER JOIN 
  e_term_taxonomy tt 
ON 
  tr.term_taxonomy_id = tt.term_taxonomy_id
INNER JOIN 
  e_terms t 
ON 
  t.term_id = tt.term_id 
WHERE
  tt.taxonomy = "category" AND 
  t.term_id IN(4,670,158)