mysql in 字符串数组_MySQL FIND_IN_SET带数组字符串

bd96500e110b49cbb3cd949968f18be7.png

I have a field in a table I am querying that looks similar to this:

Name Phone Category_IDS Category_Labels

Sample 1111111111 ["1"] ["foo", "bar"]

I am trying to use the FIND_IN_SET function to find all rows that contain one of the values listed in the comma separated list. Something like this returns nothing:

SELECT * FROM sampletable WHERE FIND_IN_SET('1', category_ids) <> 0

It does work if I do this:

SELECT * FROM factual_usplaces WHERE FIND_IN_SET('["1"]', category_ids) <> 0

But of course that limits to searches to rows where the category_ids or labels only contains a single value in the comma separated list. So ["1"] would be found but ["1", "2"] would not.

Is there a way to remove the brackets and quotations from the string on the fly in the query?

解决方案

If data is stored exactly how you showed it then you can use REPLACE() to strip double quotes and brackets before feeding category_ids to FIND_IN_SET().

SELECT *

FROM Table1

WHERE FIND_IN_SET(1, REPLACE(

REPLACE(

REPLACE(category_ids, '"', ''),

'[', ''),

']','')) > 0

Now if you will use it a lot then you may consider to create a user defined function to simplify your code

CREATE FUNCTION UNQOUTE_LIST(_list VARCHAR(512))

RETURNS VARCHAR(512)

RETURN

REPLACE(

REPLACE(

REPLACE(_list, '"', ''),

'[', ''),

']','');

And use it

SELECT *

FROM Table1

WHERE FIND_IN_SET(1, UNQOUTE_LIST(category_ids)) > 0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值