mysql - 如何将选择语句结果转换为 JSONARRAY 并更新另一个表
问题描述
我想将选择结果转换为 JSON 并将其写入另一个表:
update patrol_patrol a, position_user b
set a.route = json_array(select coordinate from b )
where a.id = 1;
并得到错误:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select coordinate from b ) where a.id = 1' at line 2
select route from patrol_patrol;
+--------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| route |
+--------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ["112.58006496213066,22.311484443420195"] |
+--------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set
select coordinate from position_user;
+---------------------------------------+
| coordinate |
+---------------------------------------+
| 112.701036,22.738611 |
| 112.701036,22.738632 |
| 112.701036,22.738632 |
| 112.701036,22.738652
position_user.coordinate 应该是 ["112.701036,22.738611", "112.701036,22.738632", "112.701036,22.738652", ....] 更新后
解决方案
由于您只更新patrol_patrol
表,因此您应该只将其包含在更新语句的第一部分中。为了得到你要找的东西,我建议使用这个JSON_ARRAYAGG
函数,它将你的结果合并到一个数组中,然后可以用来将结果分配给a.route
:
UPDATE patrol_patrol a
SET a.route = (SELECT JSON_ARRAYAGG(coordinate) FROM position_user)
WHERE a.id = 1;
可以在这里找到一个 dbfiddle 来演示这种方法。
推荐阅读
- android - 匕首可以使android活动创建速度变慢吗?
- python - 将温度转换为 int
- c# - 无法让开关功能工作以进入不同的静态类
- python - 将代码和不一致描述的 2 列数据框转换为每个唯一代码的所有可能描述的嵌套列表
- sql - 为什么脚本没有从 mosquitto 接收数据?
- java - 在 pgAdmin 控制台中获取查询结果,但不是通过我的 java 代码
- sql - Pyspark SQL/SQL 中的窗口和聚合函数
- python - Keras 错误:尺寸必须相等,但对于输入形状为 [8,10]、[8,2] 的“loss/output_1_loss/SquaredDifference”,尺寸必须为 10 和 2
- android - Agora React Native 麦克风权限
- java - 如何交换数组中的元素?