Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

Contando o número de palavras correspondentes


Não tenho certeza se é uma maneira melhor, mas é assim que eu faria:
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

Se as strings forem longas o suficiente, talvez a concatenação repetida possa levar mais tempo do que criar uma tabela derivada (improvável, mas vale a pena tentar):
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