简体   繁体   中英

How do I do this SQL SELECT statement?

I have a table called SPJ with SNo, PNo, JNo and Quantity. The SQL statement problem is:

Get the supplier number of suppliers who supply part P3 but do not supply part P5.

Now I'm sure this should be simple, but i cannot get it to return the right results!

It should just return "S3", as they are the only ones who supply part 3 but not 5, yet it always returns the number of suppliers who supply both, no matter what combination of NOT, <> etc is used.

SELECT  sno
FROM    (
        SELECT  DISTINCT sno
        FROM    spj
        WHERE   pno = 3
        ) q
WHERE   sno NOT IN
        (
        SELECT  sno
        FROM    spj
        WHERE   pno = 5
        )

Look up the EXCEPT clause.

It's a two step thing. You need to compile the list for Part 3, and have a separate list for Part 5 that is then removed. the EXCEPT clause is one way to do this. Or you can use "Where not exists"

select distinct sno  # distinct in case of duplicates
from spj A
left join spj B on A.sno = B.sno and B.pno = 5  # same supplier supplies part 5
where A.pno = 3  # supplies part 3
  and B.sno is null  # no match on left join

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM