2
$post = $wpdb->get_results("SELECT `p`.`ID`, MAX(p.post_date) as `datetime`, `p`.`post_date`, `p`.`post_content`, `p`.`post_title`, `p`.`post_status`, `p`.`post_name`, `p`.`comment_count`, `tax`.`term_taxonomy_id`, `tax`.`term_id`, `tax`.`taxonomy`, `tax`.`parent`, `rel`.`object_id`, `rel`.`term_taxonomy_id`, `t`.`term_id`, `t`.`name`, `t`.`slug`

FROM (`$wpdb->posts` AS p)

INNER JOIN `$wpdb->term_relationships` AS rel ON `rel`.`object_id` = `p`.`ID`

INNER JOIN `$wpdb->term_taxonomy` AS tax ON `tax`.`term_taxonomy_id` = `rel`.`term_taxonomy_id`

INNER JOIN `$wpdb->terms` AS t ON `t`.`term_id` = `tax`.`term_id`

WHERE `tax`.`taxonomy` =  'category'
AND `p`.`post_status` = 'publish'
AND `p`.`post_type` =  'post'

GROUP BY tax.parent

ORDER BY datetime DESC
LIMIT 4");

我需要找到每个类别的最新帖子,然后对结果进行分组,因此每个类别只有一个最新帖子。

我用; GROUP BY tax.parent不工作;ORDER BY datetime DESC

4

2 回答 2

1

您的 ID 是增量的。用那个。

select ...
from 
.....
where id post_in 
(select max(post_id) from table group by category)

如果你知道有多少类别,你可以做得更好

where post id in 
(select post_id from table where category=1 order by time desc limit 1
union
select post_id from table where category=2 order by time desc limit 1
union
select post_id from table where category=3 order by time desc limit 1
union
select post_id from table where category=4 order by time desc limit 1)

或者你可以使用参数,这会给你一个完美的结果,但查询速度很慢

select * from
(select 
@rn:=if(@prv=category_id, @rn+1, 1) as rId,
@prv:=category_id as category_id,
timestamp,
other columns
from (select category_id, timestamp, other columns from ... )a
join
(select @prv:=0, @rn:=0)tmp
order by 
category_id , timestamp desc) a
where rid<=1
于 2013-10-17T15:30:47.950 回答
0

尝试GROUP BY t.name代替 tax.parent,而MAX(p.ID)不是MAX(p.post_date). 我认为您不能在日期时间使用 MAX (可能是错误的,但它对我不起作用),而且我认为按 t.name 分组是您想要的(或 t.term_id 或 slug)。

它似乎给了我每个类别的最新帖子,但在我的情况下这可能是一个巧合。

于 2013-10-17T15:54:32.693 回答