多个字段都需要做 in 查询,而 in 的条件也都一样,并且都是通过一个子查询获取。举例来说:从一个表中查询由 30 岁以下的人创建或者修改的所有记录,可以用如下的 sql 语句:select * from table1
where creatorID in
(select userID from user where age <= 30)
or
modifierID in
(select userID from user where age <= 30)对于这样的 sql 语句,两个 in 的条件都一样,请问这样的 sql 语句能否进一步优化,如果可以,如何操作?能否将两个 in 查询减少为一个?

解决方案 »

  1.   

    select * from table1 a
    where exists(select 1 from user where age <= 30 and (a.userID=userID or a.modifierID =userID))
      

  2.   

    楼上的可以,用exists代替in还可以使用union 代替orselect * 
    from table1 a,user  b
    where a.creatorID=b.userID 
    and b.age <= 30
    union 
    select * 
    from table1 a,user  b
    where a.modifierID =b.userID 
    and b.age <= 30
    ;
     
      

  3.   


    up,用exists代替in可以提高查询效率