Mysql

從另一個表中沒有行的表中選擇數據

  • March 20, 2018

我有 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)

您想要的稱為“反連接”(或“反半連接”)。在 MySQL 中進行這種查詢有 3 種主要方法(在​​其他 DBMS 中還有更多方法,它們已經實現了EXCEPToperator):

  • 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
 ) ;
  • 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 ;
  • 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
 ) ;

引用自:https://dba.stackexchange.com/questions/201730