字符串表中的mysql搜索关键字

时间:2014-08-05 18:39:12

标签: mysql regex search words

我在产品表中有一个catID列,它包含类别ID作为字符串,

类似的东西' 142,156,146,143'

我有一个问题'?catID = 156,141,120'

我想在catID列中搜索每个id。

我使用此查询:

SELECT * FROM product WHERE catID REGEXP '156|141|120'

此代码返回在catID列中具有任何id的产品,但我想返回具有所有id的产品,

所以,我正在寻找REGEXP的运营商,但我找不到。

我想使用REGEXP或类似功能的东西来查找带有一个查询的产品,我不想使用

catID LIKE '156' AND catID LIKE '141' ....

如果是posibble。

编辑:我不想再执行一次功能,因为查询可能有100多个ID,因此编写代码会更加困难,

1 个答案:

答案 0 :(得分:2)

您需要对每个类别ID参数使用find_in_set()以便在集合中查找值,如果您可以更改模式然后对其进行规范化,方法是使另一个连接表保存此表中的关系到类别表

select * from 
product 
where 
find_in_set('142',catID ) > 0

对于像find_in_set('161,168,234,678',preferred_location ) > 0这样的多个值,不能这样做,你必须为每个位置ID执行

select * from 
product 
where 
find_in_set('142',catID ) > 0
and find_in_set('156',catID ) > 0
and find_in_set('146',catID ) > 0
and find_in_set('143',catID ) > 0 ... for more

Database normalization

find_in_set

示例架构

  • 产品(id,其他栏目)
  • 类别(id,其他列)
  • Product_categories(id,product_id,category_id)

Product_categories是一个联结表,每个产品将包含product_id和一个category_id,因此每个产品将与单个类别和单个产品保持关系

例如

产品

id  name

1  product 1
2  product 2

分类

id  name

142  category 1
156  category 2
146  category 3
143  category 4

Product_categories

id  product_id  category_id
1     1          142  
2     1          156  
3     1          146  
4     1          143  

现在你可以使用in()加入这些表和查询,如下所示,count应该等于作为参数提供的类别id的数量

select p.* from
Products p
join Product_categories pc on (p.id = pc.product_id)
where pc.category_id in(142,156,146,143)
group by p.id
having count(distinct pc.category_id) = 4

Sample Demo

或者,如果您无法将提供的类别ID计为参数,则可以通过以下查询

来执行此操作
select p.* from
Products p
join Product_categories pc on (p.id = pc.product_id)
where pc.category_id in(142,156,146,143)
group by p.id
having count(distinct pc.category_id) = 
ROUND (   
        (
            LENGTH('142,156,146,143')
            - LENGTH( REPLACE ( '142,156,146,143', ",", "") ) 
        ) / LENGTH(",")        
    ) + 1

Sample Demo 2