WordPress mysql group by |排序方式


Wordpress mysql group by | order by

$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

您的 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

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

它似乎给了我每个类别的最新帖子,但就我而言,这可能是巧合。