sql >> Base de Datos >  >> RDS >> Mysql

Contar el número de palabras coincidentes

No estoy seguro de si es una mejor manera, pero así es como lo haría:

SELECT d.id, d.word, LEFT(d.description, 100) description,
  COALESCE(sum(v.vote), 0) votecount,
    (CONCAT(word, description, `usage`) LIKE '%George%')
  + (CONCAT(word, description, `usage`) LIKE '%Tabuki%')
  + (CONCAT(word, description, `usage`) LIKE '%Street%')
  + (CONCAT(word, description, `usage`) LIKE '%Fighter%')
  + (CONCAT(word, description, `usage`) LIKE '%Miley%')
  + (CONCAT(word, description, `usage`) LIKE '%Cyrus%') `match`
FROM definition d
LEFT JOIN vote v ON v.definition_id = d.id
GROUP BY d.id
HAVING `match` > 0
ORDER BY `match` DESC, votecount DESC

Si las cadenas son lo suficientemente largas, tal vez la concatenación repetida lleve más tiempo que crear una tabla derivada (poco probable, pero vale la pena intentarlo):

SELECT id, word, description, votecount,
    (fullDesc LIKE '%George%')
  + (fullDesc LIKE '%Tabuki%')
  + (fullDesc LIKE '%Street%')
  + (fullDesc LIKE '%Fighter%')
  + (fullDesc LIKE '%Miley%')
  + (fullDesc LIKE '%Cyrus%') `match`
FROM (
  SELECT d.id, d.word, LEFT(d.description, 100) description,
    COALESCE(sum(vote), 0) votecount, CONCAT(word, description, `usage`) fullDesc
  FROM definition d
  LEFT JOIN vote v ON v.definition_id = d.id
  GROUP BY d.id
) s
HAVING `match` > 0
ORDER BY `match` DESC, votecount DESC