开发者

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')


Better to use 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜