MySQL查询查找特定列数据,但如果它包含另一个特定列数据则排除(同一列)

时间:2017-11-30 20:44:40

标签: mysql wordpress

我试图根据2件事改变wordpress数据库中的post_status。首先所有帖子必须有term_taxonomy_id = 2902,然后排除也有term_taxonomy_id = 3152的帖子

这是数据库结构:

表wpsite_posts

   Column ID
   Column post_status

表wpsite_term_relationships

   Column object_id
   Column term_taxonomy_id

ID 和列对象ID 包含这两个表之间匹配的数据..以下是一些测试查询...

SELECT *
FROM wpsite_posts
WHERE ID IN (SELECT object_id
            FROM wpsite_term_relationships
            WHERE term_taxonomy_id = 2902
                AND NOT term_taxonomy_id = 3152);

此查询返回term_taxonomy_id 2902的所有帖子,但无法忽略也有term_taxonomy_id 3152的帖子。

SELECT *
FROM wpsite_posts
WHERE ID IN (SELECT object_id
            FROM wpsite_term_relationships
            WHERE term_taxonomy_id = 2902
                AND term_taxonomy_id NOT IN (3152));

此查询返回term_taxonomy_id 2902的所有帖子,但无法忽略也有term_taxonomy_id 3152的帖子。

SELECT *
FROM wpsite_posts
WHERE ID IN (SELECT object_id
            FROM wpsite_term_relationships
            WHERE term_taxonomy_id NOT IN (3152)
                AND term_taxonomy_id = '2902');

此查询返回term_taxonomy_id 2902的所有帖子,但无法忽略也有term_taxonomy_id 3152的帖子。

实时查询看起来像这样......

UPDATE wpsite_posts
SET post_status = 'private'
WHERE ID IN (SELECT object_id
             FROM wpsite_term_relationships
             WHERE term_taxonomy_id = 2902
AND NOT term_taxonomy_id = 3152);

这不起作用,即使他们也有term_taxonomy_id 3152,也列出了term_taxonomy_id 2902的所有帖子。

我应该怎么做呢?

2 个答案:

答案 0 :(得分:1)

您无法在单个IN语句中执行此操作,因为term_taxonomy_id=2902的所有记录都不会具有值3152。您需要一个包含正对象ID的列表和一个包含负ID的列表。然后你可以包括第一组并排除最后一组。

SELECT * 
FROM wpsite_posts 
WHERE ID IN (
  SELECT object_id 
  FROM wpsite_term_relationships 
  WHERE term_taxonomy_id = 2902
)
AND ID NOT IN (
  SELECT object_id 
  FROM wpsite_term_relationships 
  WHERE term_taxonomy_id = 3152
)

答案 1 :(得分:0)

试试这个:

选择p。* FROM wpsite_posts p内连接wpsite_term_relationships t1 on p.id = t1.object_id left join(select object_id,term_taxonomy_id from wpsite_term_relationships where term_taxonomy_id = 3152)t2 on p.id = t2.object_id WHERE t1.term_taxonomy_id = 2902和t2.term_taxonomy_id为空

抱歉格式错误,通过电话发送......