简体   繁体   English

MySQL FIND_IN_SET 带数组字符串

[英]MySQL FIND_IN_SET With Array String

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.我正在尝试使用 FIND_IN_SET function 来查找包含逗号分隔列表中列出的值之一的所有行。 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.但当然,这仅限于搜索 category_ids 或标签在逗号分隔列表中仅包含单个值的行。 So ["1"] would be found but ["1", "2"] would not.所以会找到 ["1"] 但不会找到 ["1", "2"]。

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() . 如果数据的存储方式与您显示的完全相同,则可以在将category_idsFIND_IN_SET()之前使用REPLACE() FIND_IN_SET()双引号和括号。

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

Here is SQLFiddle 这是SQLFiddle


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

Here is SQLFiddle 这是SQLFiddle

try below sql query with like operator 尝试在下面的SQL查询中使用类似运算符

SELECT * FROM factual_usplaces WHERE category_ids LIKE '%1,2%' SELECT * FROM factual_usplaces WHERE category_ids LIKE'%1,2%'

Hope This help you 希望这对你有帮助

SELECT * 
  FROM Table1 
 WHERE FIND_IN_SET("bar", REPLACE(REPLACE(REPLACE(`Category_Labels`, '\"', ''), '[', ''), ']',''))

This is working for me这对我有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM