我正在尝试进行mysql查询以获得仅提供红色部分的供应商?

时间:2013-11-12 23:35:18

标签: mysql sql database relational-database

这是mysql查询

select distinct C.sid
 from Catalog C  
where not exists 
( select * from Parts P where P.pid = C.pid and P.color != 'red');

但它返回供应红色部件的供应商而不仅仅是红色部件? 和想法如何改变

我有3张桌子

Suppliers(sid: integer, sname: string, address: string) 
Parts(pid: integer, pname: string, color: string) 
Catalog(sid: integer, pid: integer, cost: real) 

任何帮助将不胜感激,谢谢

2 个答案:

答案 0 :(得分:1)

select
    sid
from
    suppliers s
where
    exists (
        select 
            'x'
        from
            catalog c
                inner join
            parts p
                on c.pid = p.pid
        where
            s.sid = c.sid and
            p.color = 'red'
    ) and
    not exists (
        select
            'x'
        from
            catalog c
                inner join
            parts p
                on c.pid = p.pid
        where
            s.sid = c.sid and
            p.color != 'red'
    )

答案 1 :(得分:0)

尝试

Select c.id
From catalog c
Where exists (
     Select 1 From Parts p
     Where p.pid = c.pid And p.color = 'red')
And not exists (
     Select 1 From Parts p
     Where p.pid = c.pid And p.color <> 'red')