【问题标题】:Get the row that contains most words of a string in a field获取字段中字符串中包含最多单词的行
【发布时间】:2021-01-26 19:06:46
【问题描述】:

在 PHP 中,我有一个字符串 $str = 'word1 word2 word3'

然后我有一个名为 content 的 mysql-db-field。

我需要哪个 MySQL 语句来获取在其content 中具有大部分 字的行 str

例子:

  • Row1 的字段:word1 word2 word1 word1 word2
  • Row2 的字段:word9 word2 word1 word8 word2
  • Row3 的字段:word1 word2 word1 word1 word3

将输出Row3,因为它包含word1word2word3

  • Row1 的字段:word1 word2 word1 word1 word2
  • Row2 的字段:word9 word2 word2 word8 word2
  • Row3 的字段:word1 word1 word1 word1 word9

将输出Row1,因为它包含word1word2

【问题讨论】:

  • 您自己尝试过什么来解决这个问题? (我认为它不能在 1 个 MySQL 语句中完成)
  • 全文索引?这是针对标签云之类的吗?
  • 术语提示:它不是 MySQL“命令”,通常称为“语句”。
  • 我看不出这个问题与 PHP 或 mysqli 有什么关系?你为什么这么坚持给它贴标签?

标签: mysql


【解决方案1】:

你可以(如果你有 MySQL8.0 或更新版本):

SET @str = 'word1 word2 word3';

DROP  TABLE IF EXISTS content;
CREATE TABLE content(i integer, str VARCHAR(200));
INSERT INTO content VALUES
    (1,'word1 word2 word1 word1 word2'),
    (2,'word9 word2 word1 word8 word2'),
    (3,'word1 word2 word1 word1 word3');

WITH RECURSIVE abc AS (
   SELECT 
      LEFT(@str,instr(@str,' ')-1) as a, 
      MID(CONCAT(@str,' '),instr(@str,' ')+1) as b
   UNION ALL
   SELECT LEFT(b,instr(b,' ')-1), MID(b,instr(b,' ')+1)
   FROM abc
   WHERE rtrim(b)<>'')
SELECT
  x.i,
  content.str,
  sum(c)
FROM (
  SELECT 
    a , 
    content.str, 
    content.i,
    (length(content.str)-length(replace(content.str,a,'')))/length(a) as c
  FROM abc
  CROSS JOIN content) x
INNER JOIN content on content.i=x.i
GROUP BY x.i;

输出:

i str sum(c)
1 word1 word2 word1 word1 word2 5.0000
2 word9 word2 word1 word8 word2 3.0000
3 word1 word2 word1 word1 word3 5.0000

WITH RECURSIVE 部分创建一个临时表 abc,其中包含许多记录作为 @str 中的单词。

之后,只需要计算出现次数即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2018-09-19
    • 2015-03-26
    • 1970-01-01
    • 2023-02-22
    • 1970-01-01
    相关资源
    最近更新 更多