代码之家  ›  专栏  ›  技术社区  ›  Reed

在逗号分隔的列中匹配精确结果

  •  0
  • Reed  · 技术社区  · 4 年前

    在SQL Server中,我有一列包含逗号分隔的id,例如:

    身份证件 产品ID
    1. ABC-1231234989123
    2. '123,XYZ'
    3. '678,ABC-123'

    如果我写一个声明

    SELECT * 
    FROM MyTable 
    WHERE ProductIds LIKE '%123%'
    

    我希望此查询只返回第2行,因为它是唯一包含CSV的行 '123' 然而,可以理解的是,它也返回了第1行和第3行,因为它是匹配的 'ABC-123' '1234' .

    我解决这个问题的最佳方法是什么?

    2 回复  |  直到 4 年前
        1
  •  4
  •   Pradeep Kumar    4 年前

    由于您没有标记任何特定的SQL Server版本,因此这里有一个适用于所有版本的SQL Server的解决方案,与 String_Split 这将需要更高的版本。

    您可以在搜索的字符串的两侧加逗号。

    SELECT * 
    FROM MyTable 
    WHERE ',' + ProductIds + ',' LIKE '%,123,%'
    
        2
  •  0
  •   Stu    4 年前

    你可以很容易地做到这一点 string_split ,类似

    select t.Id
    from MyTable
    cross apply String_Split(productids,',')
    where value='123'
    
        3
  •  0
  •   astentx    4 年前

    您可以使用 string_split 功能。但它不会将您的数据视为CSV,因此转义在这里不起作用。最好将此数据存储在1NF中。

    with a as (
    select *
    from ( values 
      (1, '''ABC-123,1234,989123'''),
      (2, '''123,XYZ'''),
      (3, '''678,ABC-123''')
    ) as t (id, productid)
    )
    select id
    from a
    where exists (
      select 1
      from string_split(trim(''''
       from a.productid), ',') as f
      where f.value = '123' 
    )
    GO
    
    | id |
    | -: |
    |  2 |
    

    db<>小提琴 here

        4
  •  0
  •   Prashu Srivastava    2 年前

    这将检查从sql server提取逗号相关数据所需的所有条件。

    SELECT * 
    FROM MyTable 
    WHERE
    ProductIds = '123'
    OR ProductIds LIKE CONCAT('%,','123',',%') 
    OR ProductIds LIKE CONCAT('%','123',',%') 
    OR ProductIds LIKE CONCAT('%,','123','%')