سؤال

I have a basic SQL question. To be able to explain it correctly.I'll give the schema of them .

Sailors(sid:integer,sname:string,rating:integer) (sid is a primary key.)

Now, the query is "Find sailors whose rating is greater than some sailor called Horatio" (there will be more than one Horatio since,sname is not a primary key)

The answer is :

SELECT *
FROM Sailors S
WHERE S.rating >ANY (SELECT S2.rating
                        FROM Sailors S2
                        WHERE S2.sname="HORATIO")

I wonder,Could I use IN instead of ANY ? IF I dont, What differs ? Is there anyone to help me ? Thanks in advance.

هل كانت مفيدة؟

المحلول

You couldn't use IN in with this subquery, because:

  1. When you say > ANY, it returns those rows from outer query where the rating is higher than the rating of ANY of the ratings returned by the subquery.
  2. If you would use IN, then it would return only those sailors who have the same rating as any of the sailor with name Horatio.

Notice that the first query may return sailors with name 'Horatio', because one sailor with a name 'Horatio' may have higher rating than another sailor with name 'Horatio'.

Also, ANY returns FALSE if subquery returns no rows.

Edit Ok, I didn't understand your question. You can't use < > = etc. operators with IN, they can only be used with ANY, SOME and ALL.

Take a look here for more information: Tim Hall about ANY, SOME and ALL

نصائح أخرى

I don't think you can use in for this, but you can use exists:

select *
from Sailors S
where
    exists (
        select *
        from Sailors S2
        where S2.sname = 'HORATIO' and S.rating > S2.Rating
    )

I don't think you want to use the IN (set inclusion) operator in this case. You'd need to find either an appropriate set of ratings or set of names. The search conditions for those sets would be the same as that of the desired result, so why bother?

The ANY, SOME, ALL operators demonstrate the high redundancy nature of the SQL language (not a desirable feature) i.e. the same result can always be achieved using many constructs, you never need to use ANY, SOME, ALL. Indeed, ANY and SOME are synonyms!

p.s. For interest, here's an alternative approach:

SELECT *
  FROM Sailors S
 WHERE S.rating > ( SELECT MIN( S2.rating )
                      FROM Sailors S2
                     WHERE S2.sname = 'HORATIO' );
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top