我将JSON字符串存储在我的数据库列中。我必须更新JSON字符串中的值。
这是我的桌子。

我想要更新其中的state值。
示例:
Name1的状态值为
KA,所以我想将其更新为GJ。
到目前为止我都试了些什么?
UPDATE Customer
SET Detail = JSON_MODIFY(Detail , '$.Address.State', 'KA')
WHERE Name = 'name1';也尝试过JSON_REPLACE也不起作用。
但它显示了错误:
FUNCTION Customer.JSON_MODIFY not 不存在
注意:我知道有一种解决方法可以做到这一点,但我不想获取该字符串并完全更新它。我想要更新字符串中的特定详细信息。
我还创建了SQL Fiddle.
我在本地主机上执行此操作。下面是localhost的详细信息。
Database server
Server: localhost (localhost via TCP/IP)
Software: MySQL
MySQL Version :5.5.24
phpMyAdmin
Version information: 3.5.1, latest stable version: 4.7.3发布于 2017-08-06 21:48:03
..。
除非另有说明,否则JSON函数是在MySQL 5.7.8中添加的。
..。
尝试:
UPDATE `Customer`
SET `Detail` = JSON_REPLACE(`Detail`, '$.Address.State', 'GJ')
WHERE `Name` = 'name1';参见db-fiddle。
发布于 2017-08-30 23:09:18
正如@wchiquito已经指出的,JSON函数是在MySQL 5.7.8中添加的。
如果您无法升级MySQL安装,则必须采用您提到的解决方法。如果不能定义自定义mysql函数,那么使用正则表达式来替换您的值也是行不通的。(如果您使用正则表达式执行这样的操作,还会出现很多错误……)
所以我看你唯一的选择就是:
对您的安装进行奖励(授予@wchiquito).
它可能看起来像这样:
// fetch the details
$sth = $pdo->prepare('select `Detail` from `Customer` where `Name` = ?');
$sth->execute(['name1']);
$detail = json_decode($sth->fetchColumn(), true);
// modify the state
$detail['Address']['State'] = 'KA';
// update the details
$sth = $pdo->prepare('update `Customer` set `Detail` = ? where `Name` = ?');
$sth->execute([json_encode($detail), 'name1']);但我建议如果可能的话,只升级你的MySQL安装。
发布于 2017-08-31 19:52:17
因为您有一个旧的MySQL,所以获取JSON字符串,将其解码为数组,编辑该数组,重新编码,并更新您的行:
// Fetch row
$json = $row['columnName'];
$array = json_decode($json, true); //true creates array and not stdClass
$array['valueToChange'] = 'some new value';
$json = json_encode($array);
// Perform update queryhttps://stackoverflow.com/questions/45532477
复制相似问题