【问题标题】:Wordpress mysql group by | order byWordpress mysql 分组 |订购
【发布时间】:2013-10-17 15:19:23
【问题描述】:
$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个分类吗?
  • 你在进行非法分组。
  • @bozdoz 是 4 个类别和帖子中的类别
  • 如果帖子属于多个类别怎么办?这将是不止一次的最新帖子。可以吗?

标签: php mysql wordpress


【解决方案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

【讨论】:

  • 谢谢,但类别 ID 不确定
  • 然后使用第一个
  • 我添加了另一个选项,但这个选项会慢一些。它将完全返回您需要的内容,只需将子查询替换为未分组的查询并输入您的列名。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2018-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多