我正在尝试在wordpress mysql数据库中列出属于几个类别的帖子。

我使用的语句如下:

SELECT *
FROM wp_term_relationships
INNER JOIN wp_posts ON wp_term_relationships.term_taxonomy_id IN (12,18,19,20,4161,4157,4160,4168,4183,4185,4188,4190,4192,4195,4199,4200,4202,4205,4332)
AND wp_term_relationships.object_id = wp_posts.ID
AND wp_posts.post_status = 'publish'


问题是有些帖子被分配到多个类别,结果中出现了很多重复。我如何只获得独特的帖子。换句话说,如果帖子已分配到多个类别,则我只需要在任何一个类别下将其列出一次。

最佳答案

仅将需要与DISTINCT语句一起显示的字段添加到sql中,还可以调整join语句。

SELECT DISTINCT wptr.object_id,
                wptr.someOtherFields,
                wp.anotherfield
  FROM wp_term_relationships wptr
            INNER JOIN wp_posts wp ON wptr.object_id = wp.ID
 WHERE wptr.term_taxonomy_id IN (12, 18, 19, 20, 4161, 4157, 4160,
                                 4168, 4183, 4185, 4188, 4190, 4192,
                                 4195, 4199, 4200, 4202, 4205, 4332)
   AND wp.post_status = 'publish'


添加DISTINCT子句本身将消除重复项。指定字段是一个很好的实践。

10-02 20:57