Mysql - 从文本中选择单词

时间:2010-10-07 13:52:59

标签: php sql mysql

我有一个包含300个地点名称的表(Pris,London,...)有没有办法(查询)从指定文本中选择位置。

例如:

“伦敦交通局(伦敦交通局)正在与其美国,澳大利亚和欧洲合作伙伴就为纽约巴黎发行单张非接触式卡片进行谈判”。

我想要查询:

  • 伦敦
  • 巴黎
  • 纽约

我试过了:SELECT name FROM coutries WHERE name IN ("Transport for London (TfL) is in talks with its American, Australian and European partners about issuing a single contactless card for Paris, New York")

但没有机会!,有人可以帮忙吗?

3 个答案:

答案 0 :(得分:4)

SELECT name 
FROM coutries 
WHERE ("Transport for London (TfL) is in talks with its American, Australian and European partners about issuing a single contactless card for Paris, New York") LIKE CONCAT('%', name, '%');

IN完全不同。

答案 1 :(得分:1)

以这种方式实现它的唯一方法是在SQL中使用类似%name的 - 如果需要,可以遍历您的名称以构建where子句,我也建议将stirng添加到变量中像我一样重复它:

SELECT name FROM countries WHERE ('Transport for London (TfL) is in talks with its American, Australian and European partners about issuing a single contactless card for Paris, New York') like '%London%' or ('Transport for London (TfL) is in talks with its American, Australian and European partners about issuing a single contactless card for Paris, New York') like '%Paris%' or ('Transport for London (TfL) is in talks with its American, Australian and European partners about issuing a single contactless card for Paris, New York') like '%New York%';

但是这样做意味着您可能会带回更多您期望的结果,因为它在该字符串中的位置并不重要;即使是另一个词的一部分。如果您传递的是完整的国家/地区名称,但是传递united之类的内容可能会返回United KingdomUnited States,那么您应该没问题。

答案 2 :(得分:0)

您可以尝试使用php首先查询数据库中的名称列表,然后将其与文本进行比较。

 // connect to the db first..

 // select the names from the db
 $sql = "SELECT names FROM countries";
 $result = mysql_query($sql) or die(mysql_error());

 // store names in an array
 $names = array();
 while($data = mysql_fetch_assoc($result)) $names[] .= $data;

然后您可以使用PHP的数组函数从文本中提取名称

 // store the text in an array per word
 $exploded_text = explode(' ',$text);

 // get the common strings (the names) from both arrays
 $extracted_names = array_intersect($exploded_text,$names);

 print_r($extracted_names);

我想有更好更有效的解决方案,但我希望你能得到这个想法。


IN用作多个OR的快捷方式,以便以下WHERE语句

WHERE (name = 'London' OR name = 'Paris' OR name = 'New York')

变为

WHERE name IN ('London','Paris','New York')