简体   繁体   中英

How to make an SQL query to test for many wildcard id's without using many statements

I have to write an SQL query to find the id's in a table which are similar to the ID's of another table.

The problem while querying from the TABLE_B is that, in TABLE_B these queries will be having some String attached to it.

For example:

If the ID passed is: 123456789

Then in TABLE_B it will be like ABC12456789XYZ

So to select these, I thought of writing an SQL query as shown below, iterating thousands of and clauses:

String idCsList = "";
int i = 1;
for( String ids : idList ) {
   if( i == 1 ) {
      idCsList = idCsList + "'%" + ids + "%'" + ")";
      i++;
      continue;
   }
   idCsList = idCsList + " AND TABLE_B.id LIKE (" + "'%" + ids + "%'" + ")";
   i++;
}

But this idea will not work because of the limit on the length of an SQL query, and the query will fail. It also takes too long.

Is there a better way to query using many wildcard operators in a more performance optimized way?

From the example you gave it looks like you can extract the table_A.id from a table_B.id with some kind of function.

  1. As a first step you can write such a function and use it in your select. But this probably doesn't help much performance wise (I might actually harm the performance) but ...

  2. You can create a function based index on table_b using the function, making it look the function value is just there in the table for the sql engine to use.

Of course this requires changes to the table ... don't know if this is possible in your case.

In SQL you can construct the string that gets passed into the LIKE :

SELECT * 
FROM TABLE_A A INNER JOIN TABLE_B B ON A.ID = B.ID
WHERE B.ID LIKE ('%' + A.ID + '%')

Select * from TABLE_A a Inner Join TABLE_B b on b.id like '%'+a.id+'%' where a.id in(idCsList)

Please use appropriate concat function for '%'+a.id+'%'

Just keep an indexed column with the ID from TABLE_A, and SELECT where prefix=id.

LIKE predicates prefixed by '%' are really expensive because you have to scan the whole table.

Have you tried others answear, like ecampver's?

you should try this assuming you're running oracle databases, simple as that:

select AID from A join B on BID like '%' || AID || '%';

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