计算匹配单词的数量

时间:2013-12-02 03:32:58

标签: php mysql

我有两个表,其中填充了此sqlFiddle

中的数据

现在,我有一个如下所示的查询,当我搜索“George Tabuki Street Fighter Miley Cyrus”时,我有php explode搜索字符串并通过添加{动态构建查询{1}}

+ CASE WHEN ... END

上面的查询完全返回我想要的内容。

问题:有没有更好的方法,或者mySQL中是否有一个返回匹配单词数量的函数?

更新

我找到了一种更好的方法,但不是更好的方法,但它会返回匹配项的出现次数

SELECT id,word,LEFT(description,100)as description, 
             IFNULL((SELECT sum(vote)
                     FROM vote v
                     WHERE v.definition_id = d.id),0) as votecount,
         0
    + CASE WHEN LOCATE('George',CONCAT(word,description,`usage`))>0 THEN 1 ELSE 0 END
    + CASE WHEN LOCATE('Tabuki',CONCAT(word,description,`usage`))>0 THEN 1 ELSE 0 END
    + CASE WHEN LOCATE('Street',CONCAT(word,description,`usage`))>0 THEN 1 ELSE 0 END
    + CASE WHEN LOCATE('Fighter',CONCAT(word,description,`usage`))>0 THEN 1 ELSE 0 END
    + CASE WHEN LOCATE('Miley',CONCAT(word,description,`usage`))>0 THEN 1 ELSE 0 END
    + CASE WHEN LOCATE('Cyrus',CONCAT(word,description,`usage`))>0 THEN 1 ELSE 0 END
as `match`
FROM definition d
HAVING `match` > 0
ORDER BY `match` DESC,votecount DESC

1 个答案:

答案 0 :(得分:2)

不确定这是否是一种更好的方法,但这就是我要做的事情:

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

如果字符串足够长可能重复连接可能比创建派生表花费更多时间(不太可能,但值得尝试一下):

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