从表 MySql 中删除数据 JSON

发布于 2025-01-18 19:43:53 字数 372 浏览 1 评论 0原文

嗨,我需要从json表中删除所有包含名称ubaus_pistol50的所有内容,这是我在mysql

> {“ auperons”中的表格之一:[{“ ammo”:74,“ name”:“ aupery_pistol50”},{ “ ammo”:118,“名称”:“ auper_pistol50”},{“ ammo”:54,“ name”:“ auper_pistol”}]}

表命名:datastore_data

和包含json格式的列为称为数据。

我想通过从json:'{“ ammo”:118,“ name”:“ duber_pistol50”}中删除此表来更新所有表,

我现在还没有测试过许多变量,但是我需要做以上。

Hi I need to remove from a json table everything that contains the name weapon_pistol50 , this is one of my tables in mysql

{"weapons":[{"ammo":74,"name":"WEAPON_PISTOL50"},{"ammo":118,"name":"WEAPON_PISTOL50"},{"ammo":54,"name":"WEAPON_PISTOL"}]}

The table is named: datastore_data

and the column that contains json format is called data.

I want to update all the tables by deleting this from the json: '{"ammo":118,"name":"WEAPON_PISTOL50"}'

I haven't tested many variables for now, but I need to do the above.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

许一世地老天荒 2025-01-25 19:43:53

这是在 MySQL 8.0 上测试的解决方案:

update datastore_data cross join json_table(data, '$.weapons[*]' 
  columns( 
    i for ordinality, 
    ammo int path '$.ammo', 
    name varchar(20) path '$.name'
  )
) as j 
set data = json_remove(data, concat('$.weapons[', j.i-1, ']')) 
where j.ammo = 118 and j.name = 'WEAPON_PISTOL50';

如果您使用的 MySQL 版本太旧而无法支持 JSON_TABLE(),那么它会困难得多。

坦率地说,如果不使用 JSON 会容易得多。相反,在第二个表中每行存储一件武器,其中普通列名为 ammoname

create table weapons(
  id serial primary key,
  owner_id int,
  ammo int,
  name varchar(20)
);

然后,您可以更简单地完成此任务:

delete from weapons
where ammo = 118 and name = 'WEAPON_PISTOL50';

在 JSON 文档中存储数据似乎是将复杂数据加载到单个表的单行中的便捷方法,但实际上您之后必须处理该数据的每项任务都会变得更加困难与使用普通表和列相比。

Here's a solution tested on MySQL 8.0:

update datastore_data cross join json_table(data, '$.weapons[*]' 
  columns( 
    i for ordinality, 
    ammo int path '$.ammo', 
    name varchar(20) path '$.name'
  )
) as j 
set data = json_remove(data, concat('$.weapons[', j.i-1, ']')) 
where j.ammo = 118 and j.name = 'WEAPON_PISTOL50';

If you are using a version of MySQL too old to support JSON_TABLE(), then it's a lot harder.

Frankly, it would be far easier if you didn't use JSON. Instead, store one weapon per row in a second table with normal columns named ammo and name.

create table weapons(
  id serial primary key,
  owner_id int,
  ammo int,
  name varchar(20)
);

Then you could do this task much more simply:

delete from weapons
where ammo = 118 and name = 'WEAPON_PISTOL50';

Storing data in JSON documents might seem like a convenient way to load complex data into a single row of a single table, but virtually every task you have to do with that data afterwards becomes a lot harder than if you had used normal tables and columns.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文