MYSQL Triggers: JSON_SEARCH an integer value in a

2020-03-12 02:48发布

I am looking to use json_search to get the array path that corresponds to a value.

I have tried and this works:

SET @j = '["3", "2", "1"]';
SELECT json_search(@j, 'one', '2');

returns $[1];

I have tried and this doesn't work: (How do I make this work?)

SET @j = '[3, 2, 1]';
SELECT json_search(@j, 'one', 2);

returns null;

Basically I want to store @j as an integer array instead of a string array for indexing purposes. Is there any way I can change the integer array into a string array for comparison if there is no way for json_search to work with integers?

3条回答
爷的心禁止访问
2楼-- · 2020-03-12 03:07

This seems to work:

SET @j = '[3, 2, 1]';
SELECT JSON_CONTAINS(@j, '3', '$');
查看更多
做个烂人
3楼-- · 2020-03-12 03:16

It is by design, although I can not agree with mySQL team. This should be implemented.

https://bugs.mysql.com/bug.php?id=79233 [closed]

The specification at https://dev.mysql.com/worklog/task/?id=7909 says: "This function returns path(s) to the given string. The returned path(s) identify object members or array slots which are character strings."

So it seems that the intention of this function was to search for strings. The documentation should be updated to clarify that the function is for searching for string scalars, not for scalars in general.

查看更多
▲ chillily
4楼-- · 2020-03-12 03:22

I have tried a workaround method, which is to CONCAT the string and cast it back to JSON and update the table. It's not the most elegant way, so if you guys have any suggestion, please let me know! :)

BEGIN
DECLARE var1 INT default -2; //offsets
DECLARE var2 INT default 2; //offsets
SELECT StatusID into @statusList FROM UserStatusesIndex;
SET @statusID_to_remove = OLD.StatusID;
SET @startIndex = INSTR(@statusList, @statusID_to_remove);
SET @charLength = CHAR_LENGTH(@statusID_to_remove);

IF @startIndex <= 2 THEN SET var1=-1, var2=2; //If its the first index
ELSEIF (CHAR_LENGTH(@statusList) - @startIndex <= 2) THEN SET var1=-3, var2=0;  //If its the last index
ELSE SET var1=-2, var2=2;
END IF;

SET @newJson=CAST(CONCAT(SUBSTRING(@statusList, 1, @startIndex+var1), SUBSTR(@statusList, @startIndex + @charLength+var2, CHAR_LENGTH(@statusList) - @startIndex - @charLength+2)) as JSON);
UPDATE UserStatusesIndex SET StatusID=@newJson WHERE StatusCreator=OLD.StatusCreator;
END

Thanks!

查看更多
登录 后发表回答