我的数据库表中有一个存储类别的文件.我按以下格式存储类别:
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条款但没有找到结果.
任何人都可以建议我一些其他选择.
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
Run Code Online (Sandbox Code Playgroud)
无论如何,你最好通过在product(main)表上添加一个类别表及其引用来重构你的模式
编辑
另一种解决这个问题的方法是使用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;
Run Code Online (Sandbox Code Playgroud)
如果匹配,这将与prod_catg正则表达式'^1,.*|.*,1$|.*,1,.*'returnig 1 (TRUE)相匹配,0 (FALSE)否则.
然后您的WHERE子句将如下所示:
WHERE prod_catg REGEXP '^1,.*|.*,1$|.*,1,.*'
Run Code Online (Sandbox Code Playgroud)
正则表达式的解释:
^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
Run Code Online (Sandbox Code Playgroud)
我确信这个正则表达式可以更加紧凑,但我对正则表达式并不是那么好
obviuosly你可以改变你正在寻找一个在正则表达式的类别(尝试更换1与7在上面的例子)
| 归档时间: |
|
| 查看次数: |
5167 次 |
| 最近记录: |