【问题标题】:SQL query to find all two word combinations查找所有两个单词组合的 SQL 查询
【发布时间】:2015-09-20 15:58:11
【问题描述】:

使用 PHP 和 MySQL,我需要从超过一百万行的表中找到按计数排序的所有“两个单词”组合。

搜索需要找到每两个词组合的实例有多少,例如“硬件商店”、“到”、“第二次机会”、“为那些”、“老年人”等。

要搜索的文本示例:

id | content
1  | The senior citizens went to the hardware store from the community center.

2  | The hardware store is offering a second chance drawing for those senior citizens who did not win.

3  | Many senior citizens go to the town's community center to play bingo.

示例结果:

senior citizens - 3
to the - 2
hardware store - 2
community center - 2
second chance - 1
The senior - 1
center to - 1
the town's - 1
etc ...and so on.

结果需要包含所有“两个单词”的组合。 “老人”、“去”、“硬件”、“市民去”等,以及找到的次数。

我猜这可能是一个带有子查询的多查询解决方案,但我的查询构建专业知识很少。我尝试了一些基本查询,但我认为解决方案会比我的技能复杂一点。

Similar question with different data source.

【问题讨论】:

  • 在 MySQL 中像这样拆分字符串非常困难。最好将所有内容检索到 PHP 中,使用 explode() 将其拆分为单词,将所有两个单词组合放入一个数组中,然后使用 array_count_values()
  • @Barmar - 是的,我也这么想,但不知道 array_count_values() ......这让它变得更简单。我现在对它进行了粗略的编码。如果您将您的评论作为答案发表,那么我会接受。

标签: php mysql


【解决方案1】:

尝试联合全部加入:

SELECT count(*) FROM your_table WHERE content LIKE '%senior citizens%'
UNION ALL
SELECT count(*) FROM your_table WHERE content LIKE '%to the%'
UNION ALL
SELECT count(*) FROM your_table WHERE content LIKE '%hardware store%'

【讨论】:

  • 谢谢,但是有超过一百万行,这就是很多 UNION。我现在得到了一个可行的解决方案,部分基于 Barmar 的评论。
猜你喜欢
  • 2019-08-20
  • 2016-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-02
  • 2012-01-11
相关资源
最近更新 更多