Search code examples
mysqlsqldatabaseshortcut

Specify table-column on "in" operator


i would like to know if there is any shortcut to specify the column where IN have to check for matches.

Example:
Instead of this:

select * 
from table1
where id in(
    select column
    from table2
) 

something like this:

select * 
from table1
where id in table2.column

I know the existence of TABLE for IN, ANY, SOME to specify a table, but it works only if the table specified is composed by just 1 column

EDIT: using join is not an option, because the real use i was looking for is on a NOT IN operator, and also JOIN create duplicates sometimes like in a one to many relation


Solution

  • There is no shortcut like that in SQL. Let me explain why.

    In a query, all table references need to be made in the FROM clause. Hence, you cannot simply refer to table2.col unless table2 has been defined in the FROM clause. table2 is actually an alias, which defaults to the table name.

    From a performance perspective, I would recommend exists:

    select t1.* 
    from table1 t1
    where exists (select column
                  from table2 t2
                  where t2.column = t1.id
                 ) 
    

    In particular, this can take advantage of an index on table2(column) and has the same semantics as in.