MSSQL:使用LIKE运算符基于条件列表筛选数据
Got it, let's break this down to get exactly the results you're looking for. First, let's recap the table structures to make sure we're aligned:
- Table1: Has a single column
Indicationswith values:Insomnia,Depression,Anxiety - Table2: Has two columns
ConditionandCode, with entries likeShort term insomnia (1),Transient insomnia (2),Chronic depression (3),Post natal depression (4)
Core SQL Query
The key here is joining the two tables using a LIKE condition that checks if Table2's Condition contains the term from Table1's Indications. We'll use CONCAT to wrap the indication term with wildcard characters (%) so it matches anywhere in the condition string:
SELECT i.Indications, c.Condition, c.Code FROM Table1 i JOIN Table2 c ON c.Condition LIKE CONCAT('%', i.Indications, '%');
What This Does
- This query returns every row from Table2 where the
Conditionincludes the corresponding term from Table1. For example:Insomniawill match bothShort term insomniaandTransient insomniaDepressionwill matchChronic depressionandPost natal depressionAnxietywon't return any results since none of Table2's conditions include that term
Handling Case Sensitivity
If your database is case-sensitive (e.g., some PostgreSQL or SQL Server configurations), you can make the match case-insensitive by converting both strings to the same case. Here's how to adjust the query:
MySQL/MariaDB:
SELECT i.Indications, c.Condition, c.Code FROM Table1 i JOIN Table2 c ON LOWER(c.Condition) LIKE CONCAT('%', LOWER(i.Indications), '%');
SQL Server/Oracle:
Use LOWER() (same as above) or UPPER()—just ensure both sides of the LIKE are converted consistently.
Quick Note
Don't forget to replace Table1 and Table2 with your actual table names if they're different!
内容的提问来源于stack exchange,提问作者HM8689

