📜  mysql select where field like in list - SQL (1)

📅  最后修改于: 2023-12-03 15:33:01.941000             🧑  作者: Mango

MySQL Select Where Field Like In List - SQL

In MySQL, the LIKE clause is used to search for a string pattern within a column. The % symbol represents any number of characters, while the _ symbol represents a single character. The IN clause is used to specify multiple values for a column.

Syntax

The following is the syntax for using the LIKE and IN clauses in a SELECT statement:

SELECT column1, column2, ...
FROM table_name
WHERE column LIKE 'pattern'
      AND column IN (value1, value2, ...);
Example

Suppose we have a table called students with the following data:

| id | name | age | gender | |----|------|-----|--------| | 1 | John | 20 | M | | 2 | Jane | 22 | F | | 3 | Mark | 20 | M | | 4 | Anna | 21 | F |

We can use the following SQL query to select all students whose names start with 'J' and are either 20 or 21 years old:

SELECT * 
FROM students 
WHERE name LIKE 'J%' 
      AND age IN (20, 21);

This will return the following result:

| id | name | age | gender | |----|------|-----|--------| | 1 | John | 20 | M |

Conclusion

The combination of LIKE and IN clauses in a SELECT statement can be quite powerful in filtering data based on certain patterns and multiple values. It is important to use them carefully and efficiently to avoid slow query execution.