与MySQL的JSON_ARRAY_APPEND相反吗?

时间:2019-04-29 22:46:57

标签: mysql json

我使用UPDATE table SET col = JSON_ARRAY_APPEND(col, '$', 'BAZ')向我的json列添加了一个值:

Before: ["FOO", "BAR"]
After: ["FOO", "BAR", "BAZ"]

我现在如何删除该值,即执行JSON_ARRAY_APPEND的相反操作?我已经尝试了以下方法,但似乎并没有获得价值。

UPDATE table SET col = JSON_REMOVE(col, '$.BAZ')

1 个答案:

答案 0 :(得分:2)

您可以按位置而不是按值删除数组元素。

import SafariServices
import UIKit

class StateDetailViewController: UIViewController, SFSafariViewControllerDelegate {


  @IBAction func watchButtonTapped(_ sender: SAButton) {
      if let url = URL(string: self.state!.url) {
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
        let safariVC = SFSafariViewController(url: url)
        let config = SFSafariViewController.Configuration()
        config.entersReaderIfAvailable = true
        self.present(safariVC, animated: true, completion: nil)
        safariVC.delegate = self
      }
  }
  @IBOutlet weak var stateTitleTextLabel: UILabel!
  @IBOutlet weak var stateDetailTextTitleLabel: UILabel!
  @IBOutlet weak var stateDescriptionTextView: UITextView!

  var state: State?

  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

  title = "Reciprocal Details"

    stateTitleTextLabel.text = state?.title
    stateDetailTextTitleLabel.text = state?.detailText
    stateDescriptionTextView.text = state?.description

  func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
      controller.dismiss(animated: true, completion: nil)
    }
  }
}

但是您可以使用JSON_SEARCH()查找位置:

select json_remove('["FOO", "BAR", "BAZ"]', '$[2]') as array;
+----------------+
| array          |
+----------------+
| ["FOO", "BAR"] |
+----------------+

您会发现它奇怪地将JSON双引号放在该路径周围。因此,您必须取消报价:

select json_search('["FOO", "BAR", "BAZ"]', 'one', 'BAZ') as path;
+--------+
| path   |
+--------+
| "$[2]" |
+--------+

然后将它们放在一起:

select json_unquote(json_search('["FOO", "BAR", "BAZ"]', 'one', 'BAZ')) as path;
+------+
| path |
+------+
| $[2] |
+------+

如果您不使用JSON数组,这会容易得多。代替使用数组,将多值属性放在子表中,每行一个值。然后,您可以使用传统的SQL删除:

select json_remove('["FOO", "BAR", "BAZ"]', json_unquote(json_search('["FOO", "BAR", "BAZ"]', 'one', 'BAZ'))) as array;
+----------------+
| array          |
+----------------+
| ["FOO", "BAR"] |
+----------------+

我已经在Stack Overflow上回答了有关在MySQL中使用JSON的许多问题,但我还没有看到使用JSON比使用标准化表更容易的实例。