SQL - 从具有公共字段的组中获取不同的记录

时间:2016-10-07 02:30:46

标签: mysql sql

我有一张桌子:supplier_product

Product , Supplier, Status
Sugar   , N_Supp,   MAIN
Sugar   , S_Supp,   SUB
Sugar   , E_Supp,   MAIN
Water   , N_Supp,   SUB
Water   , S_Supp,   SUB
Water   , W_Supp,   SUB
Milk    , S_Supp,   MAIN
Milk    , N_Supp,   MAIN
Cream   , N_Supp,   SUB
Cream   , E_Supp,   SUB 
Coffee  , S_Supp,   MAIN 
Coffee  , W_Supp,   SUB
Coffee  , N_Supp,   SUB

我必须让所有产品只有' SUB'作为状态。 我用过这段代码。但我无法弄清楚我的查询问题,结果不正确

SELECT DISTINCT
    s.product
FROM supplier_product s
WHERE EXISTS (SELECT
    *
FROM supplier_product
WHERE supplier_product.product = s.product
AND supplier_product.status = 'SUB')

应该得到以下结果:

Product
Water
Cream

如果您遇到此问题或任何链接/建议,请提供帮助。我很乐意了解它。感谢。

3 个答案:

答案 0 :(得分:2)

使用聚合最容易做到这一点:

select sp.product
from supplier_product sp
group by sp.product
having min(sp.status) = max(sp.status) and   -- the statuses are all the same
       min(sp.status) = 'SUB';               -- the value is 'SUB'

答案 1 :(得分:1)

您可以使用HAVINGGROUP BY

SELECT product
FROM supplier_product
GROUP BY product
HAVING
    SUM(CASE WHEN status = 'SUB' THEN 1 ELSE 0 END) > 0
    AND SUM(CASE WHEN status <> 'SUB' THEN 1 ELSE 0 END) = 0

ONLINE DEMO

答案 2 :(得分:-1)

select distinct product
from supplier_product
where status = 'SUB'