2011-10-07 64 views
0

我有这样一个表:如何使用关键字从表格中搜索记录?

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' 

如何搜索这样的。 。

谢谢

回答

-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

+0

那只是为搜索条件 –

+0

而且他是在说存在不翻译为LIKE“%标准%”,而是变成完全匹配的。 –

+0

我想清楚一点。如果一个**描述**包含“这是一辆好车”,那么这个记录应该被提取用于** car **关键字 – Awan

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 ''%'[email protected]_holder+'%'' or ' 
      set @where = @where+'description like ''%'[email protected]_holder+'%'' or ' 
      set @where = @where+'location like ''%'[email protected]_holder+'%'' or '+CHAR(10) 
     end 

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

    set @dyn_sql = 
    ' 
    select 
     * 
    from 
     Products 
    where 
     '[email protected] 

    exec (@dyn_sql) 
+0

感谢您的辛勤工作。我会试一下.. – Awan