1

这就是
我使用 Wordpress 类别表并有 2 个主要类别的工作方式。第一个称为“ location”,另一个称为“ subject”。这两个类别都有自己的子类别。

在我的示例中,我们有“ location”类别 17 和“ subject”类别 3。

这就是我想要做的
我只想选择同时出现我的类别 17 和 3 的数据。

到目前为止,此代码有效

SELECT term_id, post_title, post_name, ID, object_id, post_status
FROM wp_posts AS wpost
INNER JOIN wp_term_relationships
   ON wpost.ID = wp_term_relationships.object_id

INNER JOIN wp_term_taxonomy
   ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id AND wp_term_taxonomy.taxonomy = 'category'

WHERE wp_term_taxonomy.term_id IN (17, 3)
   AND post_status = 'publish'

问题
类别 17 和 3 都存在于同一列中。如果帖子出现在两个类别中,上面的代码会列出两次 ID。

有没有办法计算结果中相等的 ID?如果 ID 存在两次,请从该 ID 中选择帖子

4

3 回答 3

1

如果每个帖子都存在于两个类别中,这将只选择一次:

SELECT  post_title, post_name, post_status
FROM    wp_posts AS wpost
WHERE   post_status = 'publish'
        AND EXISTS (
        SELECT   1
        FROM     wp_term_relationships
        INNER JOIN
                 wp_term_taxonomy
        ON       wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
                 AND wp_term_taxonomy.taxonomy = 'category'
                 AND wp_term_taxonomy.term_id IN (17, 3)
        WHERE    wp_term_relationships.object_id = wpost.ID
        LIMIT 1, 1
        )
于 2009-06-02T14:54:38.690 回答
0

这样就可以做到(前提是类别 3 或 17 中的条目没有重复的行),而无需嵌套查询:

SELECT term_id, post_title, post_name, ID, object_id, post_status, COUNT(*) as count
FROM wp_posts AS wpost
INNER JOIN wp_term_relationships
   ON wpost.ID = wp_term_relationships.object_id

INNER JOIN wp_term_taxonomy
   ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id AND wp_term_taxonomy.taxonomy = 'category'

WHERE wp_term_taxonomy.term_id IN (17, 3)
   AND post_status = 'publish'
   AND count = 2

GROUP BY ID

添加count 变量和 GROUP BY 子句会将重复项聚集在一起。然后过滤计数等于 2 的行以获取两个类别中的条目。

于 2009-06-02T21:26:52.437 回答
0

更近了一步?现在我唯一需要做的就是在“count”列中显示包含“2”的行。

因为计数列是在“循环”中创建的,所以只写“AND count = 2”是行不通的。

此示例显示包含计数列的结果:

SELECT term_id, post_title, post_name, ID, object_id, post_status, COUNT(ID) as count
FROM wp_posts AS wpost
INNER JOIN wp_term_relationships
   ON wpost.ID = wp_term_relationships.object_id

INNER JOIN wp_term_taxonomy
   ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id AND wp_term_taxonomy.taxonomy = 'category'

WHERE wp_term_taxonomy.term_id IN (17, 3)
   AND post_status = 'publish'

GROUP BY ID
于 2009-06-03T07:17:04.130 回答