我在数据库中有以下表格。
users ----------------- | id | username | ----------------- | 1 | goje | | 2 | john | | 3 | henry | ----------------- comments ------------------------------------------------- | id | uid | comment | ------------------------------------------------- | 1 | 1 | One who works hard is the one who | | | | succeeds | | 2 | 1 | This one was the best. | | 3 | 2 | You are one of my best friends. | | 4 | 3 | He was the one who bought this one.| -------------------------------------------------
现在,假设给定的单词是“one”。我想有一个MySQL查询,可以让我知道users表中每个用户出现的这个单词的数量。 在这种情况下,结果应该是
-------------------- | username | count | -------------------- | goje | 3 | -> 2 in first comment and 1 in second | henry | 2 | -> 2 in henry's only comment | john | 1 | --------------------
请告诉我如何使用SQL实现此目的。谢谢!
答案 0 :(得分:3)
尝试此查询:
SELECT
users.username AS username,
round(sum((LENGTH(comments.comment) - LENGTH(REPLACE(LOWER(comments.comment),"one", ""))) / LENGTH("one")), 0) AS count
FROM users
INNER JOIN comments ON comments.uid = users.id
GROUP BY users.id
ORDER BY count DESC;
我不知道REGEXP方法是否更便宜或更昂贵。