You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写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.


1. Retrieving records matching multiple values in the same field

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.


2. Pattern matching for "Mi Bl"

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:23:49