MySQL - Select 仅在另一列中记录具有相同 ID 和特定值的记录

MySQL - Select only records with same ID and specific value in another column

我正在尝试通过 SQL 找到一种从 WooCommerce 中的数百种产品中删除特定类别的解决方案。不幸的是,Wordpress 核心仍然无法做到这一点,而且我还没有找到任何用于批量编辑 WooCommerce 产品类别的插件或代码。

我是 SQL 的新手,并尝试将我在此处找到的一些查询放在一起,但其中 none 工作正常。

如果有人知道答案,我相信会有更多人发现这个话题真的很有帮助。

我的产品有多个类别,所以 table 看起来像这样:

object_id  term_taxonomy_id
1          10
1          20
1          30
2          10
2          30
3          20
3          30
3          40
4          10
4          20

我想筛选同时具有类别 10 和 20 的产品..

object_id  term_taxonomy_id
1          10
1          20
4          10
4          20

..然后 select 只有值为 20 的行所以输出应该是这样的:

object_id  term_taxonomy_id
1          20
4          20

我希望我正在努力实现的目标是可能的。

这将 select 重复行:

SELECT
    object_id, term_taxonomy_id, COUNT(*)
FROM
    YOUR_TABLE_NAME
GROUP BY
    object_id, term_taxonomy_id
HAVING 
    COUNT(*) > 1

是的,可以使用 exists 子查询来检查分类法 id = 10 的对象:

select t1.object_id, t1.term_taxonomy_id
from yourtable t1
where t1.term_taxonomy_id=20
    and exists (select 1
                from yourtable t2
                where t2.term_taxonomy_id=10 and t2.object_id=t1.object_id)

您可以使用自连接或 in() 子查询,但存在通常更快,因为它不需要第二次获取数据。

另一种过滤方法是通过连接:

SELECT t.object_id, t.term_taxonomy_id
FROM yourtable t
    INNER JOIN yourtable t1 
        ON t.object_id = t1.object_id
        AND t1.term_taxonomy_id = 10
WHERE t.term_taxonomy_id = 20

这将使您避免由 Shadow 的答案中的 exists 子句引起的多重选择(尽管这在语义上是完全正确的)。