如何将选择语句结果转换为JSONARRAY并更新另一个表

时间:2019-10-16 03:43:15

标签: mysql arrays json

我想将选择结果转换为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”,....]

1 个答案:

答案 0 :(得分:1)

由于您仅更新patrol_patrol表,因此只应将其包括在update语句的第一部分中。为了获得所需的信息,我建议使用JSON_ARRAYAGG函数,该函数会将您的结果组合到一个数组中,然后可以将其用于将结果分配给a.route

UPDATE patrol_patrol a
SET a.route = (SELECT JSON_ARRAYAGG(coordinate) FROM position_user)
WHERE a.id = 1;

可以找到here的dbfiddle来证明这种方法。