如何编写SQL查询实现同字段多值搜索与指定模式模糊匹配?
Hey there! Let's break down these two SQL query scenarios with practical examples using your sample dataset (ID: 01-Mix Black, 02-Mix Red, 03-Mix Blue). I'll assume we're working with a table named color_mixes that has columns id and description.
If you need to pull rows where the description matches any of several specific values, the most efficient and readable approach is using the IN clause. For example, to get all records where description is either "Mix Black" or "Mix Red":
SELECT id, description FROM color_mixes WHERE description IN ('Mix Black', 'Mix Red');
Alternatively, you could use multiple OR conditions, but IN is far cleaner—especially when dealing with more than two values:
SELECT id, description FROM color_mixes WHERE description = 'Mix Black' OR description = 'Mix Red';
Both queries will return the rows with IDs 01 and 02 from your dataset.
To find records where the description matches the pattern "Mi Bl" (meaning it contains "Mi" followed by any characters, then "Bl"), use the LIKE operator with wildcard characters (%, which represents zero or more characters):
SELECT id, description FROM color_mixes WHERE description LIKE 'Mi%Bl%';
This query will match "Mix Black" (since "Mi" starts "Mix", followed by "x ", then "Bl" starts "Black") and exclude "Mix Red" and "Mix Blue".
Note: If your database is case-sensitive (like PostgreSQL by default) and you want to match regardless of case (e.g., "mix black" or "MI BL"), use a case-insensitive variant:
- PostgreSQL:
ILIKE 'Mi%Bl%' - MySQL:
LIKE 'Mi%Bl%'(works with most default case-insensitive collations) - SQL Server:
LIKE 'Mi%Bl%' COLLATE SQL_Latin1_General_CP1_CI_AS
内容的提问来源于stack exchange,提问作者Abbas Hodroj

