这就是我想要做的:
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
SQL无效。 the_match
不是有效的列。我正在尝试显示WHERE
子句中的哪个条件导致匹配。我该怎么办?
答案 0 :(得分:2)
您可以使用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
。
答案 1 :(得分:2)
您不能直接这样做(如您所见)。解决此类问题的一种方法是在选择列表中使用具有相同条件的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 :(得分:1)
将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
既有“好”又有“好”,那么the_match
就是“好”。