如何使用关键字从表中搜索记录?

时间:2011-10-07 14:04:21

标签: php mysql sql full-text-search

我有一张这样的表:

Products ( 'id', 'name', 'description', 'location' )

搜索字符串:

'car 1000 london'

现在我想做的是:

bring all records where 'car' exists in 'name' or 'description' or 'location'
and
bring all records where '1000' exists in 'name' or 'description' or 'location'
and
bring all records where 'london' exists in 'name' or 'description' or 'location'

我怎样才能像这样搜索..

由于

2 个答案:

答案 0 :(得分:1)

这是一个动态查询,可以执行您想要的操作。

    declare @search nvarchar(max)
    declare @dyn_sql nvarchar(max)
    declare @where nvarchar(max)

    set @search = 'car 1000 london'
    set @search = rtrim(LTRIM(@search))
    set @search = REPLACE(@search,' ',',')
    set @where = ''

    while (LEN(@search) > 0)
        begin
            declare @place_holder nvarchar(100)

            if((select CHARINDEX(',',@search)) = 0)
                begin
                    set @place_holder = @search
                end
            else
                begin
                    set @place_holder = SUBSTRING(@search, 0, CHARINDEX(',',@search))
                end

            set @place_holder = REPLACE(@place_holder,',','') 

            if((select CHARINDEX(',',@search)) = 0)
                begin
                    set @search = ''
                end

            set @search = SUBSTRING(@search, CHARINDEX(',',@search)+1, LEN(@search))

            set @where = @where+'name like ''%'+@place_holder+'%'' or '
            set @where = @where+'description like ''%'+@place_holder+'%'' or '
            set @where = @where+'location like ''%'+@place_holder+'%'' or '+CHAR(10)
        end

    set @where = SUBSTRING(@where,0,len(@where)-3)

    set @dyn_sql = 
    '
    select
        *
    from
        Products
    where
        '+@where

    exec (@dyn_sql)

答案 1 :(得分:-1)

在InnoDB中

  SELECT * FROM products p 
  WHERE (p.name LIKE '% car %' 
     OR p.description LIKE '% car %' 
     OR p.location LIKE '% car %')
UNION 
  -- same query but with '% 1000 %'
UNION 
  -- ditto with '% london %'

在MyISAM中

  SELECT 
    MATCH (p.name, p.location, p.description) AGAINST('car') as relevance,
    p.* FROM products p
   WHERE MATCH (p.name, p.location, p.description) AGAINST('london')   
   ORDER BY relevance DESC
UNION 
  -- same query but with '1000' <<-- see note below
UNION 
  -- ditto with 'car'           <<-- see note below.

Match against的最小长度为5个字符,请参阅:

http://dev.mysql.com/doc/refman/5.5/en/fulltext-restrictions.html