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

标签 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 中寻找 and 运算符,但找不到。

我想使用 REGEXP 或类似的函数提供通过一个查询查找产品的功能,但我不想使用

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

如果可能的话。

编辑:我不想再次执行某个功能,因为查询可能有 100+ id,因此编写代码变得更加困难,

最佳答案

您需要对每个类别 id 参数使用 find_in_set() 以便查找 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、其他列)
  • 产品类别(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

产品类别

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

现在您可以使用 in() 连接这些表并进行如下查询,并且计数应等于作为参数提供的类别 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

关于mysql在字符串表中搜索关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25146040/

相关文章:

mysql - 将具有相同列的不同 MySQL 表上的数据组合并合并为唯一行并对其运行查询

Javascript 正则表达式匹配不起作用

ruby-on-rails-3 - 如何修复 Rails 3 中的 Request-URI Too Large 错误?

linux - 使用 mac 终端或脚本搜索 linux 日志文件

php - 非常大的表的索引 - 性能基础信息

php - Javascript 到 PHP PDO 到 MySQL 查询返回空

mysql - mySQL中的计算列基于计算后的另一列

javascript - 使用正则表达式替换删除 bb 代码

使用正则表达式更新 mysql

search - 遍历 HashMap