简体   繁体   English

在多个表中搜索关键字

[英]Searching keywords in Multiple tables

I have the following tables, 我有下表

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

I want to search all the tables for a given keyword. 我想在所有表中搜索给定的关键字。

I tried using LIKE, which is returning many rows, 我尝试使用LIKE,它将返回很多行,

The code i tried, 我尝试过的代码

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%' 

Any help? 有什么帮助吗?

If you want to query an exact match, use = : 如果要查询完全匹配,请使用=

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' 

If you want to return all rows with the "apple" word, try to add blanks around it like that : 如果要返回所有带有“ 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 %'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM