2013-10-17 48 views
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"); 
$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"); 

我需要找到每個類別的最新帖子,然後對結果進行分組,因此我只爲每個類別提供一個最新帖子。Wordpress mysql group by |通過

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

+1

你知道有4個類別嗎? – bozdoz

+0

你正在做非法分組。 – AdrianBR

+0

@bozdoz是4個類別和類別後 – DerinSular

回答

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 
+0

謝謝但是類別ID不確定 – DerinSular

+0

然後使用第一個 – AdrianBR

+0

我添加了另一個選項,但是這個選項會更慢。它會返回你需要的東西,只要用你的未分組查詢來替換子查詢並放入你的列名。 – AdrianBR

0

嘗試GROUP BY t.name而不是tax.parent和MAX(p.ID)而不是MAX(p.post_date)。我不認爲你可以在日期時間使用MAX(可能是錯誤的,但它不適合我),我認爲按t.name分組是你想要的(或t.term_id或slug)。

它似乎給了我每個類別的最新帖子,但對我而言可能是巧合。