选择属于一个主机的所有项目

时间:2013-05-08 22:53:20

标签: mysql sql

我有以下关系

Supplies            
sid     1       2       3       4
sname   Jason   David   John    Peter
address 1a      2b      3c      4d


Parts                       
pid     10      20      30      40      50
pname   Head    Body    Hand    Leg     Arm
color   red     blue    green   white   red


Catalog             
sid     1   1   2   2   3   4   1   1   4   4   1
pid     10  20  20  30  30  40  30  40  10  50  50
cost    100 200 150 150 130 125 50  180 123 126 120

我想选择供应每个红色或绿色部分的供应商的sid。 我认为这意味着it not exist that green or red parts that not supplied by him.

所以我做了以下查询,但它返回null,我认为它应该返回sid是1。

SELECT S.sid
FROM Suppliers S
WHERE NOT 
EXISTS (

SELECT P.pid
FROM Parts P
WHERE P.color = 'red' OR P.color = 'green'
AND NOT 
EXISTS (

SELECT C.pid
FROM Catalog C
WHERE C.pid = P.pid
AND C.sid = S.sid
)
)

我该如何解决?提前谢谢。

2 个答案:

答案 0 :(得分:2)

如果您想要供应红色和绿色部件的供应商,那么您可以使用类似于此的查询:

select s.sid
from supplies s
inner join catalog c
  on s.sid = c.sid
inner join parts p
  on c.pid = p.pid
where p.color in ('red', 'green')
group by s.sid
having count(distinct p.color) = 2;

请参阅SQL Fiddle with Demo

或者@ypercube指出的更好的方式:

select s.sid
from supplies s
left join catalog c
  on s.sid = c.sid
left join parts p
  on c.pid = p.pid
 and p.color in ('red', 'green')
group by s.sid
having count(distinct p.pid) = (select count(*)
                                from parts 
                                where color in ('red', 'green'));

请参阅SQL Fiddle with Demo

答案 1 :(得分:1)

您的查询是正确的,但OR中缺少的括号会导致错误的结果(AND的优先级高于OR)。它应该是:

WHERE (P.color = 'red' OR P.color = 'green')

或:

WHERE P.color IN ('red', 'green')