简体   繁体   中英

How do i do this simple SQL SELECT statement?

I'm having trouble with what I think should be the simplest of SQL statements, however it is not working for me...

I have 4 tables: S, P, J and SPJ where SPJ is basically a table linking all the ID's together.

Now, the statement required is: "Get supplier numbers for suppliers who supply part P2 and part P4."

SELECT SNO FROM SPJ WHERE PNO = 'P2' AND PNO = 'P4'
- returns no results (which is wrong)

SELECT SNO FROM SPJ WHERE PNO = 'P2' UNION SELECT SNO FROM SPJ WHERE PNO = 'P4'
- returns the result, plus an extra which only supplies one of the two...

I've tried all manner of statements but can't figure it out, I know it's got to be simple, but I just can't see it...

Anybody got any ideas?

Cheers

This will get you suppliers who provide both parts, as opposed to those who supply either/or.

select sno
    from spj
    where pno in ('P2','P4')
    group by sno
    having count(distinct pno) = 2

Or as an alternative to @Sathya

SELECT SNO 
FROM SPJ 
WHERE PNO = 'P2'
OR PNO = 'P4'
SELECT SNO FROM SPJ WHERE PNO in ('P2','P4')

最好使用OR

SELECT SNO FROM SPJ WHERE PNO = 'P2' OR PNO= 'P4'

"SELECT SNO FROM SPJ WHERE PNO = 'P2' AND PNO = 'P4'"

obviously PNO can't be both P2 and p4 at the same time. it's difficult to answer your question without a knowing the db scheme, you should give a description of your tables.

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