Search code examples
mysqlin-operator

MySQL LIMIT inside IN Operator


select distinct column1 
from Table1 
where Table1id in ((select T2.Table1id 
                    from Table2 T2 
                    where (conditions) 
                    order by T2.column) 
                   limit 2
                  );

I cannot use limit inside the In operator. Do we have any other way to limit inside IN operator? Or do we have any other way without using IN and also without using any joins?

Error (while using limit inside the In Operator):-

Error Code: 1235. This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'


Solution

  • For non-specific MySQL versions, Ergest gave you a good solution of using JOIN. Here is another workaround in which an outer layer is used on top of the derived table.

    select distinct column1 
    from Table1 
    where Table1id in (select id 
                       from 
                           (select  T2.Table1id as id
                            from Table2 T2 
                            where (conditions) 
                            order by T2.column 
                            limit 2) tb);
    

    PS: this trick can be used to bypass the ERROR 1093 (HY000): You can't specify target table 'terms' for update in FROM clause