0

我有一个非常奇怪的问题。

我只想选择两个给定类别中的所有帖子。

这是我的 SQL:

SELECT  wp_posts.ID 
FROM wp_posts 
INNER JOIN wp_term_relationships ON wp_posts.ID = wp_term_relationships.object_id
WHERE  wp_term_relationships.term_taxonomy_id  = 83  
   AND   wp_term_relationships.term_taxonomy_id  = 84

这应该返回一个结果,但它不返回任何内容。

如果我注释掉:

*wp_term_relationships.term_taxonomy_id  = 83* 

我正在寻找的帖子被退回。

如果我注释掉:

*wp_term_relationships.term_taxonomy_id  = 84*

再次,帖子被退回。

那么,为什么当这两个条件都包含时,什么都不返回呢?

任何帮助将不胜感激。谢谢

4

5 回答 5

2

wp_term_relationships.term_taxonomy_id不可能=83和在=84同一时间。

试试这个:

SELECT  
  wp_posts.ID 
FROM wp_posts 
INNER JOIN wp_term_relationships ON wp_posts.ID = wp_term_relationships.object_id
WHERE  wp_term_relationships.term_taxonomy_id IN (83 , 48);

或者

...
WHERE wp_term_relationships.term_taxonomy_id  = 83  
   OR wp_term_relationships.term_taxonomy_id  = 84;

但是,我认为您正在寻找那些同时具有term_taxonomy_id'id 83、84 的帖子,在这种情况下,您正在寻找关系部门;这是一种方法:

SELECT  
  wp_posts.ID 
FROM wp_posts 
INNER JOIN
(
   SELECT *
   FROM wp_term_relationships
   WHERE object_id IN (SELECT object_id
                       FROM  wp_term_relationships
                       WHERE term_taxonomy_id IN (83 , 48);
                       GROUP BY objecT_id
                       HAVING COUNT(term_taxonomy_id ) = 2)
)  t ON wp_posts.ID = t.object_id;

或:直接,不带JOIN. 像这样:

SELECT  
  wp_posts.ID 
FROM wp_posts 
WHERE ID IN
(
    SELECT object_id
    FROM  wp_term_relationships
    WHERE term_taxonomy_id IN (83 , 48);
    GROUP BY objecT_id
    HAVING COUNT(term_taxonomy_id ) = 2
);
于 2013-01-10T10:45:54.780 回答
1

如果您想返回所有term_taxonomy_id与它们相关联的帖子,您可以使用:

SELECT  p.ID 
FROM wp_posts p
INNER JOIN wp_term_relationships r
  ON p.ID = r.object_id
WHERE  r.term_taxonomy_id IN (83, 84)
GROUP BY p.ID 
HAVING count(distinct r.term_taxonomy_id) =2

这将返回具有两个分类术语的所有记录。

您的查询将不起作用,因为term_taxonomy_id不能同时具有两个值。您可以将查询更改为使用ORAND也可以使用我提供的版本。

于 2013-01-10T10:47:15.270 回答
0

如果您希望结果显示属于这两个类别的帖子,则需要获取两个结果并进行比较:

SELECT a.ID
FROM   (
        SELECT  wp_posts.ID 
        FROM wp_posts 
        INNER JOIN wp_term_relationships ON wp_posts.ID = wp_term_relationships.object_id
        WHERE  wp_term_relationships.term_taxonomy_id  = 83
        ) a
        INNER JOIN (
                    SELECT  wp_posts.ID 
                    FROM wp_posts 
                    INNER JOIN wp_term_relationships ON wp_posts.ID = wp_term_relationships.object_id
                    WHERE wp_term_relationships.term_taxonomy_id  = 84
                    ) b
            ON a.ID = b.ID
于 2013-01-10T10:46:16.047 回答
0

我假设您需要使用“OR”而不是“AND”。我的猜测是,您不是在寻找 taxonomy_id 为 83 和 84 的帖子,而是在寻找两者之一的帖子?

于 2013-01-10T10:46:32.077 回答
0

您的查询说:

WHERE  wp_term_relationships.term_taxonomy_id  = 83  
AND    wp_term_relationships.term_taxonomy_id  = 84

这不会返回任何内容,我怀疑您应该将 AND 更改为 OR

于 2013-01-10T10:46:39.303 回答