2011-08-12 23 views
3

我在我的數據庫表中存儲了一個存儲類別的域。我存儲的格式如下類別:Mysql中的LIKE子句的替代方案

1,12,15

現在,當我嘗試從1類搜索產品, 我用LIKE子句中我的查詢,如

where (prod_catg LIKE %1,% or prod_catg LIKE %1% or prod_catg LIKE %,1%)

這將返回所有三個類別1,12和15的產品。相反,我只想要類別1的產品。

我也有嘗試IN條款但未找到結果。

任何人都可以請建議我一些其他的選擇。

+4

你應該通過添加一個表'category'來標準化你的scema,然後在主表中引用它 – Dalen

回答

5
prod_catg LIKE '1,%' --matches when 1 is the first category 
OR prod_catg LIKE '%,1,%' --matches when 1 is somewhere in the middle 
OR prod_catg LIKE '%,1' --matches 1 when is the last category 

反正你最好通過在產品中添加的類別表的基準它(主)表

編輯

另一種方式來面對這個問題就是重構你的架構使用REGEXP這將導致更短的WHERE條款(在這裏就是我用來測試):

DECLARE @regexp VARCHAR(100); 
SET @regexp = '^1,.*|.*,1$|.*,1,.*'; 

SELECT 
    '1,11,15,51,22,31' REGEXP @regexp AS test1, 
    '51,11,15,1,22,31' REGEXP @regexp AS test2, 
    '11,15,51,22,31,1' REGEXP @regexp AS test3, 
    '7,11,15,51,22,31' REGEXP @regexp AS test4, 
    '51,11,15,7,22,31' REGEXP @regexp AS test5, 
    '11,15,51,22,31,7' REGEXP @regexp AS test6; 

這將匹配您的prod_catg與正則表達式'^1,.*|.*,1$|.*,1,.*' returnig 1 (TRUE)如果匹配則爲0 (FALSE)否則。

那麼你的WHERE子句將看起來像:正則表達式的

WHERE prod_catg REGEXP '^1,.*|.*,1$|.*,1,.*' 

解釋:

^1,.* --matches 1 at the beginning of a string followed by a `,` and any other char 
.*,1$ --matches 1 at the end of a string preceded by a `,` and any other char 
.*,1,.* --matches 1 between two `,` which are sourrounded by any other chars 
| --is the OR operator 

我敢肯定,這個正則表達式可能會更加緊湊,但我不與普通的好表達式

obviuosly您可以在正則表達式中更改要查找的類別(嘗試用替換爲7的示例le以上)

3

您有一個多對多產品和類別之間的關係。您應該創建一個新表來存儲每個產品的相關類別(cat_ids)。你不應該有一個包含多個類別標識的列。這樣你的選擇會更容易,更快。

3
WHERE FIND_IN_SET('1', prod_catg)