Mysql concat并在多个表上搜索

时间:2013-05-15 00:51:06

标签: mysql concat

我有2个表,产品和类别定义如下:

表:类别 - category_id,类别

表:产品 - product_id,category_id,item_no,description

我正在尝试将描述和类别连接到一个可搜索的字段中。当我执行以下操作时,它可以工作,但是代码很笨重:

SELECT *, concat(description, ' ',category) as searchable 
FROM products, categories 
where concat(description, ' ',category) like '%flowers%' 
and concat(description, ' ',category) like '%rainbow%' 
and products.category_id=categories.category_id order by products.category_id

所以我正在尝试编写一个像这样的子查询:

SELECT *
FROM products, categories, 
(SELECT concat(description, ' ',category) as searchable 
FROM products, categories 
where products.category_id=categories.category_id 
group by product_id) as sub
where searchable like '%flowers%' and searchable like '%rainbow%' 
and products.category_id=categories.category_id order by products.category_id;

此查询为每个product_id返回多个不正确的结果,当我尝试按product_id分组时,每个结果都会显示不正确的可搜索字段。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

有时关键是要简化。以下内容将查找具有与'%rainbow%'匹配的描述或类别的产品。

通过将查询分解为两个LIKE子句,我们还通过消除繁重的CONCAT操作来提高性能。

SELECT p.*
FROM products AS p 
LEFT JOIN categories AS c ON p.category_id = c.category_id 
WHERE p.description LIKE '%rainbow%'
    OR c.category LIKE '%rainbow%'
GROUP BY p.product_id