如何在另一列中找到两个值之间的共享值?

时间:2016-09-21 10:46:36

标签: sql

我需要列出S2和S4发货的零件供应商名称。我有3个名为S,P和SP的表,但S和SP是我需要的唯一表。

SP表

sno | pno | 
s1    p1
s2    p1
s2    p2
s4    p2
s4    p4
s4    p5

S表

sno | sname 
S1    Smith
s2    Jones
s4    Clarke

我到目前为止:

SELECT s.sname FROM s INNER JOIN sp ON s.sno = sp.sno 

3 个答案:

答案 0 :(得分:0)

请你试试这个:

SELECT sname
FROM s WHERE sno IN (SELECT MAX(sno) FROM sp 
                    GROUP BY pno HAVING COUNT(DISTINCT(sno)) > 1)

答案 1 :(得分:0)

试试这个:

apiRoutes

答案 2 :(得分:0)

  

我需要列出S2和S4发货的零件供应商名称

s2和s4发货的零件:

select pno
from sp
where sno in ('s2','s4')
group by pno
having count(distinct sno) = 2;

运送这些零件的供应商:

select distinct sno
from sp
where pno in 
(
  select pno
  from sp
  where sno in ('s2','s4')
  group by pno
  having count(distinct sno) = 2
);

完整查询这些供应商的供应商名称:

select sname 
from s
where sno in
(
  select sno
  from sp
  where pno in 
  (
    select pno
    from sp
    where sno in ('s2','s4')
    group by pno
    having count(distinct sno) = 2
  )
);