我怎么知道我的哪个结果满足了多少条件/
SELECT
[TITLE]
FROM
[M_TIPS]
WHERE
[TITLE] LIKE '%VALUE%' OR
[TITLE] LIKE '%SQL%';
如何知道哪个结果仅满足1 OR条件以及哪个结果满足两个条件。条件的数量不是静态的,它可以增加。
有人可以帮忙吗?
答案 0 :(得分:3)
将其添加到结果中:
SELECT
[TITLE]
case [TITLE] LIKE '%VALUE%' WHEN true then 1 else 0 end as CONTAINS_VALUE
case [TITLE] LIKE '%SQL%' WHEN true then 1 else 0 end as CONTAINS_SQL
FROM
[M_TIPS]
WHERE
[TITLE] LIKE '%VALUE%' OR
[TITLE] LIKE '%SQL%';
答案 1 :(得分:1)
如果使用OR,WHERE子句*中的短路可能会阻止任何匹配计数超过1。
如何将匹配列表存储在表变量中,然后计算匹配项;
DECLARE @MATCH TABLE (SCORE INT, TOKEN VARCHAR(16))
INSERT @MATCH
SELECT 1, 'VALUE'
UNION SELECT 1, 'SQL'
UNION SELECT 1, 'CAKE'
SELECT
[TITLE], SUM(M.SCORE)
FROM
[M_TIPS] T INNER JOIN @MATCH M ON T.[TITLE] LIKE '%' + M.TOKEN + '%'
GROUP BY T.[TITLE]
==
sql 1
value 1
xx sql value xx 2
答案 2 :(得分:0)
假设您正在使用编程语言动态生成具有所需生成条件的查询,那么我建议生成查询,如下所示:
SELECT [TITLE], SUM([CONDITION_COUNT]) FROM
(SELECT [TITLE], 1 [CONDITION_COUNT] FROM [M_TIPS]
WHERE [TITLE] LIKE ConditionString1 UNION ALL
SELECT [TITLE], 1 [CONDITION_COUNT] FROM [M_TIPS]
WHERE [TITLE] LIKE ConditionString2 UNION ALL
...
SELECT [TITLE], 1 [CONDITION_COUNT] FROM [M_TIPS]
WHERE [TITLE] LIKE ConditionStringN) SQ
GROUP BY [TITLE]