简体   繁体   中英

What is the precedence of conditions in where clause?

I'm using MySQL. I have a table called instructor with id,name,dept_name,salary as the attributes. I have written a query to 'find all the instructors whose salary is greater than at least one instructor in the Physics department' as

select t.name, t.dept_name, t.salary
from instructor t, instructor s
where t.salary > s.salary and s.dept_name='physics';

Now which condition will be applied first?

The entire WHERE condition will be applied, meaning that in order for a record to appear in the result set it will have to meet both the salary and department requirements.

You query looks almost correct, except that you probably want to include DISTINCT to make sure you don't report the same instructor more than once in your result set:

select distinct t.name, t.dept_name, t.salary
from instructor t
inner join instructor s
    on t.salary > s.salary and s.dept_name='physics'

You will notice that I have also replaced your implicit join syntax with an explicit inner join . You should avoid putting commas into the from clause, as this is a very old school way of doing a join which is considered deprecated by modern RDBMS.

As Tim mentioned in his answer, the entire where criteria is considered. I also commented to him that I think what you are asking for are instructors from other departments that have a salary greater than anyone in the physics dept. If you have 3 people in physics, all with different salaries, then two people have salaries greater than the lowest paid physics, but all 3 could be higher than everyone else at the school.

This would be better handled with a subquery to find the lowest physics dept salary first, then look for anyone greater than that value...

Also, the way you have it, you are going to have a Cartesian comparison since there is no JOIN condition. Every record in the instructor table is compared to every record in the SECOND instructor table (including the record it is being compared to.)

To resolve this, the second from alias below is precalculating the lowest salary ONCE for the physics department, then applying that ONE answer to all other instructor salaries that are NOT in the physics department.

select 
      t.name, 
      t.dept_name, 
      t.salary
   from 
      instructor t,
      ( select min( ps.salary ) PhysicsLowest
           from instructor ps
           where ps.dept_name='physics' ) as Phys
   where
          t.salary > Phys.PhysicsLowest
      AND NOT t.dept_name = 'physics'

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