Home > Database > Mysql Tutorial > How Can a Temporary Table Improve Efficiency When Using Multiple LIKE Conditions in SQL?

How Can a Temporary Table Improve Efficiency When Using Multiple LIKE Conditions in SQL?

Mary-Kate Olsen
Release: 2025-01-08 14:12:40
Original
1043 people have browsed it

How Can a Temporary Table Improve Efficiency When Using Multiple LIKE Conditions in SQL?

Use temporary tables to handle multiple conditions in the LIKE operator

In SQL, the LIKE operator is used to perform pattern matching on string values. Although it is possible to combine multiple LIKE conditions using the OR operator, a better solution is to use a temporary table.

Consider the following statement:

select * from tbl where col like ('ABC%','XYZ%','PQR%');
Copy after login

This statement is designed to retrieve all rows in the tbl table where the col column matches any pattern ABC%, XYZ% or PQR%. While using OR is an efficient approach, for a large number of conditions it can become tedious and inefficient.

Instead, we can create a temporary table called patterns to store all the patterns we want to match:

CREATE TEMPORARY TABLE patterns (
  pattern VARCHAR(20)
);

INSERT INTO patterns VALUES ('ABC%'), ('XYZ%'), ('PQR%');
Copy after login

After creating the temporary table, we can join it with the tbl table using the LIKE operator:

SELECT t.* FROM tbl t JOIN patterns p ON (t.col LIKE p.pattern);
Copy after login

In this query, the pattern column in the patterns table is used to match the col column in the tbl table. The result is a list of rows in tbl that match any pattern in the patterns table.

It is important to note that if a row in the tbl matches multiple patterns, it will appear multiple times in the results. If this is not desired, you can use the DISTINCT query modifier:

SELECT DISTINCT t.* FROM tbl t JOIN patterns p ON (t.col LIKE p.pattern);
Copy after login

This will ensure that each row in the tbl only appears once in the results, even if it matches multiple patterns.

The above is the detailed content of How Can a Temporary Table Improve Efficiency When Using Multiple LIKE Conditions in SQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template