带有和不带字边界的文本中的mysql搜索查询

时间:2014-07-29 04:46:19

标签: mysql

我有一个产品表,我用简单的子句搜索,我想用边界搜索,没有边界结果。

SELECT *
FROM products 
WHERE title LIKE '%cold%'

例如,如果此查询返回以下行,

coldrum
rum cold
coldwine
cold wind

我想要这样的结果(首先是边界,没有边界的休息)

cold wind
rum cold
coldrum
coldwine

嗯,实际的SQL是这样的,

select SQL_CALC_FOUND_ROWS distinct p.*, pd.*, m.*, i.image, if(s.status,
s.specials_new_products_price, null) as specials_new_products_price, if(s.status,
s.specials_new_products_price, if (pv.products_price, pv.products_price,
p.products_price)) as final_price from products p left join products_variants pv on
(p.products_id = pv.products_id and pv.is_default = 1) left join manufacturers m 
using(manufacturers_id) left join specials s on (p.products_id = s.products_id) left
join products_images i on (p.products_id = i.products_id and i.default_flag = 1),
products_description pd, categories c, products_to_categories p2c where 
p.products_status = 1 and p.products_id = pd.products_id and pd.language_id = 1 and
p.products_id = p2c.products_id and p2c.categories_id = c.categories_id and
(pd.products_tags like '%gold%' or pd.products_name like '%gold%') order by
p.products_date_added desc limit 0, 20

2 个答案:

答案 0 :(得分:1)

试试这个

SELECT *
FROM products  
WHERE title LIKE '%cold%'order by 
case when title like 'cold %' then 0 
when title like '% cold' then 1 else title end

答案 1 :(得分:0)

试试这个:

SELECT * FROM products WHERE title LIKE '%cold%' ORDER BY 
(LENGTH(title) - LENGTH(REPLACE(title, ' ', ''))+1) DESC;

SqlFiddle