在1 n关系中查找不存在的SQL查询

时间:2013-08-12 04:40:56

标签: mysql sql

我有两个表产品表和状态表

并且有1吨关系

Product table
----------------------
id    | product
1           XYZ
2           ABC
3           HJK
4           PQR
5           SWE

----------------------

status_table
--------------------------------
id  | col1 | col2 | priduct_id
2      s1     ss1      2
3      s2     xs1      3   
5      s1     ss1      3          
4      s1     xs1      4
4      s3     xs2      4
4      s2     ss2      4
4      s3     xs2      4                 
5      ww     sw2      5                   
-------------------------------------

我想选择状态NOT EQUAL = S3

的所有产品

我试过这个

select product_Table.product from product_Table
inner join status_table on 
product_table.id = status_table.id
where status_table.col1 <> 's3'

5 个答案:

答案 0 :(得分:1)

一个简单的LEFT JOIN应该这样做,它将status_table中的行与状态s3匹配到每个产品,如果不存在匹配状态,则返回产品;

SELECT DISTINCT p.id, p.product
FROM product_table p
LEFT JOIN status_table s
  ON p.id = s.product_id
 AND s.col1 = 's3'
WHERE s.id IS NULL

答案 1 :(得分:0)

你的表格设计(命名等)有很多不一致之处,但无论如何,你是否尝试过以下方面:

SELECT *
FROM Product
WHERE id NOT IN
 ( SELECT priduct_id
   FROM status_table
   WHERE col1 <> 'S3');

答案 2 :(得分:0)

尝试:

SELECT P.id, Product, col1
FROM Product P
INNER JOIN status_table S
ON P.id = S.product_id
WHERE S.col1 <> 's3'

答案 3 :(得分:0)

试试这个:

select product_Table.product from product_Table
inner join status_table on 
product_table.id = status_table.id
where 
status_table.col1 <> 's3'
group by 
product_Table.product

请检查My Demo

答案 4 :(得分:0)

如果您不介意取回没有状态关联的产品(例如“XYZ”),请尝试使用

SELECT p.id, p.product FROM Product p
WHERE NOT EXISTS (
    SELECT 1 FROM status_table s
    WHERE s.priduct_id = p.id
    AND s.col1 = 's3'
)