注意:我建议您将值放入自己的表中。仅仅将它们粘贴在查询文本中可能并不理想。但我在下面介绍的查询对于真实表和硬编码派生表同样适用。
这是一种方法:
SELECT
sum(score * multiplier) score,
title
FROM
(
SELECT 3 score, 'a railway employee' term UNION ALL
SELECT 2, 'a railway' UNION ALL
SELECT 2, 'railway employee' UNION ALL
SELECT 1, 'a' UNION ALL
SELECT 1, 'railway' UNION ALL
SELECT 1, 'employee'
) terms
CROSS JOIN (
SELECT 'title' which, 1 multiplier
UNION ALL SELECT 'summary', 1.1
) X
INNER JOIN tableName ON
CASE
X.which WHEN 'title' THEN title
WHEN 'summary' THEN summary
END
LIKE concat('%', terms.term, '%')
GROUP BY title
ORDER BY score DESC
;
这是另一种基本相同但稍微改组的方式:
SELECT
sum(terms.score * T.multiplier) score,
title
FROM
(
SELECT 3 score, 'a railway employee' term UNION ALL
SELECT 2, 'a railway' UNION ALL
SELECT 2, 'railway employee' UNION ALL
SELECT 1, 'a' UNION ALL
SELECT 1, 'railway' UNION ALL
SELECT 1, 'employee'
) terms
INNER JOIN (
SELECT
title,
CASE
X.which WHEN 'title' THEN title
WHEN 'summary' THEN summary
END comparison,
X.multiplier
FROM
tableName
CROSS JOIN (
SELECT 'title' which, 1 multiplier
UNION ALL SELECT 'summary', 1.1
) X
) T ON T.comparison LIKE concat('%', terms.term, '%')
GROUP BY title
ORDER BY score DESC
;
最后,还有一种方法:
SELECT *
FROM
(
SELECT
sum(
terms.score * (
CASE WHEN T.title LIKE concat('%', terms.term, '%') THEN 1 ELSE 0 END
+ CASE WHEN T.summary LIKE concat('%', terms.term, '%') THEN 1.1 ELSE 0 END
)
) score,
title
FROM
tableName T
CROSS JOIN (
SELECT 3 score, 'a railway employee' term UNION ALL
SELECT 2, 'a railway' UNION ALL
SELECT 2, 'railway employee' UNION ALL
SELECT 1, 'a' UNION ALL
SELECT 1, 'railway' UNION ALL
SELECT 1, 'employee'
) terms
GROUP BY title
ORDER BY score DESC
) Z
WHERE
Z.score > 0
;
此外,如果 MySQL 有类似的东西CROSS APPLY
会让它CROSS JOIN
有一个外部引用,那么其中一些会变得更容易(例如,第一个查询可能会完全丢失 CASE 语句)。