如何在另一个表列值中获取没有此列值的行

S.M*_*ian 1 mysql sql

我有一张这样的表:

Tb_Product_Options

Product_Id     Option_Id
    1              5
    1              7
    2              3
    3              9
    3              6 
Run Code Online (Sandbox Code Playgroud)

现在我想得到所有Product_Ids 都没有这个值:'5,9'。在这个例子中我的结果必然是:2product_id

Yog*_*rma 5

您可以聚合:

select Product_Id
from table t
group by Product_Id
having sum ( Option_Id in (5,9) ) = 0;
Run Code Online (Sandbox Code Playgroud)

如果你想要所有的列,那么你可以使用NOT EXISTS

select t.*
from table t
where not exists (select 1 
                  from table t1 
                  where t1.Product_Id = t.Product_Id and t1.Option_Id in (5,9)
                 );
Run Code Online (Sandbox Code Playgroud)