2011-10-07 75 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