SQL multiple在同一列上选择

时间:2016-04-12 10:49:31

标签: mysql

如下图所示,我根据OR选择帖子。我想将其更改为AND但是当我这样做时,我没有返回任何记录。有人可以帮忙吗?

由于

enter image description here

3 个答案:

答案 0 :(得分:1)

你可能想要这样的东西:

SELECT p.post_title,
       r.object_id
FROM wp_term_relatiosnhips AS r
LEFT OUTER JOIN wp_posts AS p ON p.ID = r.object_id
WHERE r.term_taxonomy_id IN (6, 10)
GROUP BY p.post_title,
         r.object_id 
HAVING COUNT(DISTINCT CASE 
                         WHEN r.term_taxonomy_id IN (6, 10) 
                         THEN r.term_taxonomy_id 
                      END) = 2 

上述查询将返回p.post_title, r.object_id对与两个 6, 10 term_taxonomy_id值相关的值,即基于您的示例数据的Buy Annual Leave, 2789。< / p>

答案 1 :(得分:0)

如果您不想使用,或者您可以使用AND IN子句

select 
  wp_posts.post:title,
  wp_term_relationships.object_id,
  wp_ter_relationships.term_taxonomy_id
from wp_term_relationships
  left outer join wp_posts
     on (wp_term_relationships.object_id = wp_posts.ID 
           and wp_term_relationships.term_taxonomy in (6,10));

答案 2 :(得分:0)

我假设你想从wp_term_relationships中的多个匹配行的wp_posts中检索记录。

我正在努力想象一下你所提供的查询中左连接的目的是什么。我会假设它的功能没有一些隐藏且非常模糊的逻辑。

考虑:

SELECT *
FROM wp_posts AS wpp
INNER JOIN wp_term_relationships AS wtr1
   ON wpp.id=wtr1.object_id
INNER JOIN wp_term_relationships AS wtr2
   ON wpp.id=wtr2.object_id
WHERE wtr1.term_taxonomy_id=6
AND wtr2.term_taxonomy_id=10;

(或使用Giorgos描述的方法)