如果查询中只有一个特定标记,则对其进行过滤

reg*_*gie 6 mysql tags wordpress post

根据标签查询wordpress帖子可能看起来像这样(如果我将它拼凑在一起 - 我从查询中删除了不相关的部分):

SELECT wposts.ID AS ID,
wposts.post_title, wposts.post_status, wposts.post_name,
tag_terms.term_id AS tag_id

FROM `wp_posts` AS wposts

INNER JOIN wp_term_relationships AS tag_term_relationships ON (wposts.ID = tag_term_relationships.object_id)
INNER JOIN wp_term_taxonomy AS tag_term_taxonomy ON (tag_term_relationships.term_taxonomy_id = tag_term_taxonomy.term_taxonomy_id AND tag_term_taxonomy.taxonomy = 'post_tag')
INNER JOIN wp_terms AS tag_terms ON (tag_term_taxonomy.term_id = tag_terms.term_id)

WHERE wposts.ID = '12345'

AND wposts.post_type = 'post'

AND wposts.post_status NOT LIKE 'private'

AND tag_terms.term_id = '55'

GROUP BY wposts.ID
ORDER BY wposts.post_date ASC
Run Code Online (Sandbox Code Playgroud)

这应该查询标签为55的所有帖子.

我需要做的是过滤掉所有仅包含此单个标记但不包含其他标记的帖子.

所以我想显示一个帖子,如果它有标签23,34,55,67但我不想显示帖子,如果它有标签55(没有其他标签).不包含此特定标记的帖子也应包含在查询中.

我该怎么做呢?

pio*_*trm 4

尝试在和HAVING之间添加条件:GROUP BYORDER BY

...
GROUP BY wposts.ID
HAVING COUNT( tag_terms.term_id ) <> 1
  OR MAX( tag_terms.term_id ) <> 55
ORDER BY wposts.post_date ASC
Run Code Online (Sandbox Code Playgroud)

并更改您的WHERE条件以仅检查帖子类型和状态。

此外,如果您没有从 wp_terms 加入中选择除 tag_id 以外的任何内容,则没有必要,因为您可以只使用 wp_term_taxonomy 中的 term_id。