2014-10-18 15 views
0

我有以下表搜索关键字,在多个表

state : state_id, state_name 
city : city_id, city_name, state_id 
category : category_id, category_name 
products : product_id, product_name, cateogory_id, product_description, city_id 

我要搜索所有表,某个关键字。

我使用等,其返回很多行,

我试过代码,

keyword = 'apple'; 

SELECT 
    * 
FROM 
    products AS p, 
    categories AS cat, 
    city AS c, 
    state as s 
WHERE 
    p.category_id=cat.category_id 
    AND p.city_id=c.city_id 
    AND c.state_id=s.state_id 
    AND p.product_name LIKE '%apple%' 
    OR p.product_description LIKE '%apple%' 
    OR cat.category_name LIKE '%apple%' 
    OR c.city_name LIKE '%apple%' 
    OR s.state_name LIKE '%apple%' 

任何帮助试过吗?

回答

0

如果您想查询完全匹配,使用=

SELECT 
    * 
FROM 
    products AS p, 
    categories AS cat, 
    city AS c, 
    state as s 
WHERE 
    p.category_id=cat.category_id 
    AND p.city_id=c.city_id 
    AND c.state_id=s.state_id 
    AND p.product_name = 'apple' 
    OR p.product_description = 'apple' 
    OR cat.category_name LIKE = 'apple' 
    OR c.city_name LIKE = 'apple' 
    OR s.state_name LIKE = 'apple' 

如果你想用“苹果”字返回所有行,尝试添加它周围的空白这样的:

SELECT 
    * 
FROM 
    products AS p, 
    categories AS cat, 
    city AS c, 
    state as s 
WHERE 
    p.category_id=cat.category_id 
    AND p.city_id=c.city_id 
    AND c.state_id=s.state_id 
    AND p.product_name LIKE '% apple%' 
    OR p.product_name LIKE '%apple %' 
    OR p.product_description LIKE '% apple%' 
    OR p.product_description LIKE '%apple %' 
    OR cat.category_name LIKE '% apple%' 
    OR cat.category_name LIKE '%apple %' 
    OR c.city_name LIKE '% apple%' 
    OR c.city_name LIKE '%apple %' 
    OR s.state_name LIKE '% apple%' 
    OR s.state_name LIKE '%apple %'