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

如何显示哪个条件匹配?

  •  0
  • Flux  · 技术社区  · 5 年前

    以下是我想做的:

    SELECT
      id, text, the_match
    FROM
      comments
    WHERE
      (lower(text) LIKE '%excellent%'
       OR lower(text) LIKE '%great%'
       OR lower(text) LIKE '%good%') AS the_match
    ORDER BY len(text) ASC
    

    the_match 不是有效列。我正在尝试显示当前的状态 WHERE 从句引起了一场比赛。我该怎么做?

    3 回复  |  直到 5 年前
        1
  •  2
  •   Mureinik    5 年前

    你不能直接这样做(正如你所看到的)。解决这类问题的一种方法是使用 case 在“选择”列表中具有相同条件的表达式:

    SELECT
      id, text, CASE WHEN lower(text) LIKE '%excellent%' THEN 'excellent condition'
                     WHEN lower(text) LIKE '%great%'     THEN 'great condition'
                     WHEN lower(text) LIKE '%good%'      THEN 'good condition'
                END AS condition
    FROM
      comments
    WHERE
      (lower(text) LIKE '%excellent%'
       OR lower(text) LIKE '%great%'
       OR lower(text) LIKE '%good%') AS the_match
    ORDER BY len(text) ASC
    

    SELECT    id, text, condition
    FROM      (SELECT id, 
                      text, 
                      CASE WHEN LOWER(text) LIKE '%excellent%' THEN 'excellent'
                           WHEN LOWER(text) LIKE '%great%'     THEN 'great'
                           WHEN LOWER(text) LIKE '%good%'      THEN 'good'
                      END AS condition
               FROM   comments ) t
    WHERE    condition IS NOT NULL
    ORDER BY LEN(text) ASC
    
        2
  •  2
  •   Tim Biegeleisen    5 年前

    你可以用一个 CASE

    SELECT
        id,
        text,
        CASE WHEN LOWER(text) LIKE '%excellent%' THEN 'excellent'
             WHEN LOWER(text) LIKE '%great%'     THEN 'great'
             WHEN LOWER(text) LIKE '%good%'      THEN 'good' END the_match
    FROM comments
    WHERE
        LOWER(text) LIKE '%excellent%' OR
        LOWER(text) LIKE '%great%' OR
        LOWER(text) LIKE '%good%'
    ORDER BY
        LEN(text);
    

    相反,如果您希望为数据库中的每个记录都添加一个标签 comments WHERE 条款在这种情况下 the_match 现场将是 NULL 对于不匹配的记录。

        3
  •  1
  •   Bohemian    5 年前

    翻译 where 变成 case :

    SELECT
      id, text, 
      case
        when lower(text) LIKE '%excellent%' then 'excellent'
        when lower(text) LIKE '%great%' then 'great'
        else 'good' end as the_match
    FROM
      comments
    WHERE
      lower(text) LIKE '%excellent%'
       OR lower(text) LIKE '%great%'
       OR lower(text) LIKE '%good%'
    ORDER BY len(text) ASC
    

    注意 the_match 返回找到的优先级最高的字。如果 text 既有“好”又有“好” 将是“伟大的”。