0

我有以下格式的 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 & 作为通配符。

4

1 回答 1

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;
于 2013-08-27T21:57:37.950 回答