vdo*_*nis 2 mysql select if-not-exists
我有2张桌子。首先"product" (id)
。第二- "product_has_option_value" (product_id, option_value_id)
。
我怎样才能获得id
没有一些的产品option_value_id
(例如 10)?“product_has_option_value”具有多对多关系。
好的。我想我找到了解决方案:
select p.id
from product p
where p.id not in
(select distinct(product_id)
from product_has_option_value
where option_value_id=543)
Run Code Online (Sandbox Code Playgroud)
你想要的是“反连接”(或“反半连接”)。在 MySQL 中有 3 种主要方法可以执行此类查询(在其他已实现EXCEPT
运算符的DBMS 中还有更多方法):
NOT IN
子查询(DISTINCT
此处不需要,但您可能需要检查AND pov.product_id IS NOT NULL
该列是否可为空):
select p.id
from product as p
where p.id not in
( select pov.product_id
from product_has_option_value as pov
where pov.option_value_id = 543
and pov.product_id is not null
) ;
Run Code Online (Sandbox Code Playgroud)LEFT JOIN
带IS NULL
支票:
select p.id
from product as p
left join product_has_option_value as pov
on pov.option_value_id = 543
and pov.product_id = p.id
where pov.product_id is null ;
Run Code Online (Sandbox Code Playgroud)NOT EXISTS
相关子查询:
select p.id
from product as p
where not exists
( select 1
from product_has_option_value as pov
where pov.option_value_id = 543
and pov.product_id = p.id
) ;
Run Code Online (Sandbox Code Playgroud)