0
votes

We have an requirement where we need to search multiple tables(more then 20) for records which matches condition. Its an Sybase database and we execute query using JDBC.

We need to form an single query so that in a single query execution we get all required data from multiple tables and we will need not to execute query multiple time for all tables.

There is no relationship between these tables.They are just log tables.

Example:

Tables : table1, table2, table3, table4

Need to get data similar to below one

select column1,column2,column3,column4 
from table1, table2, table3. table4 
where (table1.column1 or table2.column1 or table3.column1 or table4.column1) in (1,2,3,4)

so in whichever table we find id column matching to (1,2,3,4) needs to be fetched. The records will be present in any one of the many tables only.

1

1 Answers

1
votes

Use union (or union all if you want to accept duplicates)

select t1.column1, t1.column2, t1.column3, t1.column4 from table1 t1 
    where t1.column1 in (1, 2, 3, 4)
union
select t2.column1, t2.column2, t2.column3, t2.column4 from table2 t2 
    where t2.column1 in (1, 2, 3, 4)
union
...