如何查找给定句子中的列值? MySQL的

时间:2016-09-04 06:00:22

标签: php mysql sql

考虑以下mysql表

id         name
-----      ------
1          Mark
2          Mike
3          Paul
4          John

考虑输入句子

Mark and Paul are very good friends since 2000.

预期输出

Mark , Paul

我想找到输入句子中的名字。 mysql是否提供了查找此选项的任何选项。或任何想法?

3 个答案:

答案 0 :(得分:1)

这可以通过两种方式实现。使用mysql的'IN'和'REGEX'运算符。

使用“IN”运算符

<?php

$string = "Mark and Paul are very good friends since 2000.";
$sql_in = "'".implode("','",explode(" ",$string))."'";

//Will return all the records for which name match with any word in given sentence.
$mysql_query = "select * from table_name where name in($sql_in)";

?>

使用'REGEX'

<?php

$string = "Mark and Paul are very good friends since 2000.";
$regex_string = str_replace(' ','|',$string);

//Will return all the records for which name match with any word in given sentence.
$mysql_query = "select * from table_name where name REGEX '^(".$regex_string.")'";

?>

答案 1 :(得分:0)

我不知道mysql有一些选择。但您可以拆分字符串并搜索名称。

$sentence = "Mark and Paul are very good friends since 2000."

//some code to get all names from the database
//simulation mysql-output as array
$names = array("Mark", "Mike", "Paul", "John");

//first split the String into a array what contains all words of the sentences
$array = explode(" ", $sentence);

//now you can check if any words in the array eqauls a name in your database
//create a foreach loop to check all words
foreach($array as $word) {

    //search if the word contains in the array
    if(in_array($word, $names)) {
        //this word is a searched name
        print_r("Word ".$word." is a name!\n");
    }
    else {
        //this word isn't a name
    }
}

在If / Else中,您可以编写一个custum处理程序。请注意,如果句子以一个点结尾,那么最后一个单词在最后一个字符处有一个点(。)。您可以使用substr功能检查并删除点。

我没有测试代码。

答案 2 :(得分:0)

尝试存储过程。我已经测试了这个随机段落的查询,并通过三个选项获得了执行时间

 CREATE PROCEDURE FindInDB
    @INSTR varchar(255) 
 AS
 BEGIN
    SET NOCOUNT ON;

    DECLARE @SEPERATOR as VARCHAR(1)
    DECLARE @SP INT
    DECLARE @VALUE VARCHAR(1000)
    SET @SEPERATOR = ' '

    -- Create Temporary table add all words in it 
    CREATE TABLE #tempTab (name varchar(50) not null)
    WHILE PATINDEX('%' + @SEPERATOR + '%', @INSTR ) <> 0 

    BEGIN
      SELECT  @SP = PATINDEX('%' + @SEPERATOR + '%',@INSTR)
      SELECT  @VALUE = LEFT(@INSTR , @SP - 1)
      SELECT  @INSTR = STUFF(@INSTR, 1, @SP, '')
      INSERT INTO #tempTab (name) VALUES (@VALUE)
    END

  -- Total execution time   15      0       7.5000

 --SELECT [Name]
 --FROM [tblName] 
 --where Name  IN (SELECT name FROM #tempTab)

 --Total execution time 15      15      0       10.0000

 --SELECT distinct [tblName].[Name]
 --FROM [tblName] 
 --inner join #tempTab on #tempTab.name = tblName.Name;

 --Total execution time 15      15      15      15      0       12.0000

 SELECT [Name]
 FROM [tblName] 
 where EXISTS (SELECT name FROM #tempTab 
 where #tempTab.name = tblName.Name )

 DROP TABLE #tempTab
 END
 GO