Pop the last item in a JSON Array in MySQL 5.7

核能气质少年 提交于 2020-01-02 08:11:46

问题


I've got an array of dates in a field called from. It can look something like this.

['2016-05-01', '2016-05-03', '2016-05-04']

I want to SELECT the last item (here 2016-05-04).

I've tried this:

SELECT `from`->"$[JSON_LENGTH(`from`) - 1]" FROM `table` WHERE `id` = 3;

but got that error:

ERROR 3143 (42000): Invalid JSON path expression. The error is around character position 2.

I've tried using a variable like this :

SET @count = (SELECT JSON_LENGTH(`from`) - 1 FROM `table` WHERE `id` = 3);
SELECT `from`->"$[@count]" FROM `table` WHERE `id` = 3;

but got the exact same error. But if I do:

SELECT `from`->"$[2]" FROM `table` WHERE `idx` = 3;

It works fine.


回答1:


you can use :

SELECT JSON_EXTRACT(`from`,CONCAT("$[",JSON_LENGTH(`from`)-1,"]"))      FROM `table`;

to get the last item in a json array.



来源:https://stackoverflow.com/questions/38443307/pop-the-last-item-in-a-json-array-in-mysql-5-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!