总结MySQL查询中匹配的LIKE语句的数量

时间:2013-08-27 21:53:17

标签: mysql sql-like

我有以下格式的MySQL查询:

SELECT * 
FROM `table` 
WHERE `val1` IN (x,y,z)
AND (
  `val2` LIKE '%a%' OR
  `val2` LIKE '%b%' OR
  `val2` LIKE '%c%' OR
  ...
  `val2` LIKE '%x%'
)

我想要做的是将LIKE语句匹配的次数加起来。例如,如果它找到a,e和y的匹配,那么它的总数将是3,然后我可以使用ORDER BY来搜索具有最多"命中"的行。

编辑:我想念使用%as&在我的查询中作为通配符。

1 个答案:

答案 0 :(得分:0)

你可以在MySQL中将它们一起添加:

SELECT *,
       ((`val2` LIKE '&a&') +
        (`val2` LIKE '&b&') +
        (`val2` LIKE '&c&') +
        ...
       ) as nummatches
FROM `table` 
WHERE `val1` IN (x,y,z)
AND (
  `val2` LIKE '&a&' OR
  `val2` LIKE '&b&' OR
  `val2` LIKE '&c&' OR
  ...
  `val2` LIKE '&x&'
)

实际上,您可以将查询简化为:

SELECT *,
       ((`val2` LIKE '&a&') +
        ( `val2` LIKE '&b&') +
        (`val2` LIKE '&c&') +
        ...
       ) as nummatches
FROM `table` 
WHERE `val1` IN (x,y,z)
having nummatches > 0;