2

我正在寻找编写一个自定义 SQL 语句,该语句将从匹配 2 个不同类别的 Wordpress 数据库中提取已发布的帖子。

Category 1 (Static) = "Website-1"
Category 2 (Dynamic) = "News", "Tips", "Recreation", etc.

这有点超出我的领域,所以任何帮助将不胜感激。
这是我到目前为止所拥有的:

select p.* from wp_terms wt
    join wp_term_taxonomy t on wt.term_id = t.term_id
    join wp_term_relationships wpr on wpr.term_taxonomy_id = t.term_taxonomy_id
    join wp_posts p on p.id = wpr.object_id
where
    t.taxonomy = 'category' and
    wt.name = 'Website-1' and
    p.post_status = 'publish'
group by p.id
order by p.post_date desc
limit 10

它将拉第一个类别没问题,但我需要它匹配 2 个类别。

任何见解将不胜感激。

谢谢!

我想出的解决方案:

select p.* from wp_posts p 
join wp_term_relationships tr on p.id = tr.object_id
join wp_term_taxonomy tt on tt.term_taxonomy_id = tr.term_taxonomy_id
join wp_terms t on t.term_id = tt.term_id

where p.id in 
    (select tr2.object_id from wp_term_relationships tr2
     join wp_term_taxonomy tt2 on tt2.term_taxonomy_id = tr2.term_taxonomy_id
     join wp_terms t2 on t2.term_id = tt2.term_id
     where 
     tt2.taxonomy = 'category' and
     t2.name in ('Website-1') and
     p.id = tr2.object_id
) and
p.post_status = 'publish' and
tt.taxonomy = 'category' and
t.name in ('News')
group by p.id
order by p.post_date desc
limit 10

我确信有更好的方法来编写这个查询,因为它非常混乱,但它现在可以工作。

4

1 回答 1

0

尝试group by 之后而不是where 。我会将其添加为问题/评论,但我没有足够的分数......如果您切换类别的顺序会发生什么?

于 2013-10-29T03:25:09.683 回答