【问题标题】:How to select rows that begin with any word found in list?如何选择以列表中找到的任何单词开头的行?
【发布时间】:2020-01-12 12:56:38
【问题描述】:

我有一个名为 Assets 的表,每一行都有一个名为 Category 的列。一些类别名称可能如下所示...

Fruit
Fruit-Apple
Fruit-Orange
Vegetable
Vegetable-Carrot
Vegetable-Lettuce
Dairy-Cheese
Dairy-Milk

如何选择所有以('Fruit' 或 'Dairy')开头的行?我通常会使用 Like,但我不知道在使用可能的模式列表进行过滤时如何使用它?

我希望我的查询结果是这样的:

Fruit
Fruit-Apple
Fruit-Orange
Dairy-Cheese
Dairy-Milk

此 SELECT 仅适用于完整的类别值匹配

SELECT tags FROM Assets WHERE category in ('Fruit','Dairy') AND tags is not ""

【问题讨论】:

    标签: sql sqlite select sql-like


    【解决方案1】:

    你可以使用or:

    where category like 'Fruit%' or category like 'Dairy%'
    

    SQLite 具有支持正则表达式的扩展。如果您正在使用它:

    where category regexp '^(Fruit|Dairy)'
    

    【讨论】:

    • 我希望你的正则表达式方法可以工作,但它没有
    【解决方案2】:

    使用CTE 包含您要比较表中的类别的所有类别前缀:

    with cte(category) as (values ('Fruit'), ('Dairy'))  
    select a.category
    from assets a inner join cte c
    on a.category like c.category || '%' 
    

    请参阅demo
    如果你想使用正则表达式,你可以使用GLOB

    select *
    from assets  
    where category glob '[Fruit,Dairy]*'
    

    请参阅demo
    结果:

    | category     |
    | ------------ |
    | Fruit        |
    | Fruit-Apple  |
    | Fruit-Orange |
    | Dairy-Cheese |
    | Dairy-Milk   |
    

    【讨论】:

      猜你喜欢
      • 2012-10-01
      • 2015-02-07
      • 2020-08-15
      • 1970-01-01
      • 2020-03-16
      • 2016-11-02
      • 2019-08-08
      • 2020-03-15
      • 1970-01-01
      相关资源
      最近更新 更多