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

MSSQL:使用LIKE运算符基于条件列表筛选数据

Matching Table2 Conditions to Table1 Indications with LIKE Operator

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 Indications with values: Insomnia, Depression, Anxiety
  • Table2: Has two columns Condition and Code, with entries like Short 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 Condition includes the corresponding term from Table1. For example:
    • Insomnia will match both Short term insomnia and Transient insomnia
    • Depression will match Chronic depression and Post natal depression
    • Anxiety won'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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:14:48