2017-06-16 174 views
0

我有一個MySQL JSON場(交互),它保存的值是這樣的:MySQL的JSON場json_remove()

{"likes": 
    [ 
     ['1:scott'], 
     ['2:james'] 
    ] 
} 

我希望能夠刪除的對象之一。像這樣的東西(這顯然是行不通的,因爲它是一個值,而不是一個鍵):

update `user` 
set `post` = JSON_REMOVE(interactions, '$.likes."[2:james]"') 
where `id` = 3 

完成後:

{"likes": 
    [ 
     ['1:scott'] 
    ] 
} 

我一直在敲打我的腦袋上徹夜狂歡,並試圖根據在這裏和其他地方發現的各種帖子提出解決方案,沒有將一些東西拼湊在一起的運氣,這些東西給我的確是我需要的東西。任何幫助表示感謝,謝謝!

+0

只是想明白,因爲我第一次使用它:你可以運行它並告訴我這是什麼回報? ** update'user' set'post' = JSON_REMOVE('interactions','$ .likes') 其中'id' = 3 和JSON_EXTRACT('interactions','$ .likes.2')='james '** –

+0

JSON路徑表達式無效。錯誤是圍繞字符位置9. –

+0

請加入此[聊天室](http://chat.stackoverflow.com/rooms/146828/chat-for-mysql-json-field-json-remove) –

回答

0

,您可以使用一個選項將顯示在下面的腳本:(取決於表可能有性能問題,根據需要進行調整的行數):

mysql> DROP TABLE IF EXISTS `user`; 
Query OK, 0 rows affected (0.00 sec) 

mysql> CREATE TABLE IF NOT EXISTS `user` (
    -> `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
    -> `post` JSON, 
    -> `interactions` JSON 
    ->); 
Query OK, 0 rows affected (0.00 sec) 

mysql> INSERT INTO 
    -> `user` (`post`, `interactions`) 
    -> VALUES 
    -> (
    ->  '{"likes": [["1:scott"],["3:kitty"]]}', 
    ->  '{"likes": [["1:scott"],["3:kitty"]]}' 
    -> ), 
    -> (
    ->  '{"likes": [["2:james"],["1:scott"]]}', 
    ->  '{"likes": [["2:james"],["1:scott"]]}' 
    -> ), 
    -> (
    ->  '{"likes": [["1:scott"],["2:james"]]}', 
    ->  '{"likes": [["1:scott"],["2:james"]]}' 
    -> ); 
Query OK, 3 rows affected (0.00 sec) 
Records: 3 Duplicates: 0 Warnings: 0 

mysql> SET @`search` := '2:james'; 
Query OK, 0 rows affected (0.00 sec) 

mysql> UPDATE `user` 
    -> SET `post` = COALESCE(JSON_REMOVE(`interactions`, LEFT(
    ->  JSON_UNQUOTE(
    ->  JSON_SEARCH(`interactions`, 
    ->     'one', 
    ->     @`search`, 
    ->     NULL, 
    ->     '$.likes') 
    -> ), 
    ->  CHAR_LENGTH(
    ->  JSON_UNQUOTE(
    ->   JSON_SEARCH(`interactions`, 
    ->      'one', 
    ->      @`search`, 
    ->      NULL, 
    ->      '$.likes'))) - 3)), `interactions`) 
    -> -- WHERE `id` = 3 
    -> ; 
Query OK, 2 rows affected (0.00 sec) 
Rows matched: 3 Changed: 2 Warnings: 0 

mysql> SELECT 
    -> `id`, 
    -> `post`, 
    -> `interactions` 
    -> FROM 
    -> `user`; 
+----+---------------------------------------+---------------------------------------+ 
| id | post         | interactions       | 
+----+---------------------------------------+---------------------------------------+ 
| 1 | {"likes": [["1:scott"], ["3:kitty"]]} | {"likes": [["1:scott"], ["3:kitty"]]} | 
| 2 | {"likes": [["1:scott"]]}    | {"likes": [["2:james"], ["1:scott"]]} | 
| 3 | {"likes": [["1:scott"]]}    | {"likes": [["1:scott"], ["2:james"]]} | 
+----+---------------------------------------+---------------------------------------+ 
3 rows in set (0.00 sec) 

db-fiddle