简体   繁体   中英

Working with a JSON array of objects in MYSQL

I have an SQL table:

CREATE TABLE pu_events(
  int eid AUTO_INCREMENT PRIMARY KEY, 
  varchar(20) title,
  varchar(255) description, 
  int(11) start_date UNSIGNED,
  int(11) end_date UNSIGNED,
  timestamp created DEFAULT CURRENT_TIMESTAMP,
  json members
)

I plan on populating the members field with a members json object which will be an array of objects containing the user id (uid) and status of attending members, such as:

{members: [{uid:1, status:0}, {uid:2, status:1}]}

But I'm having trouble finding any resources which describe how to correctly reference this object structure to manipulate it, for example if i wish to 'register' a user to the event, to append their object to the array of members like: (members.push({uid:3, status:0}), or to update the status of a given user once they are confirmed or resign from the event, like: (update members set status = 2 where uid = 1;).

I understand that the pseudo-c I've used is a combination of js & mysql, and i also understand that MySQL now has JSON functions for manipulating this datatype, but I'm confused with the best way to approach this particular use case.

Many thanks for any advice in advance!

The proper solution is to create another table:

CREATE TABLE pu_event_members (
 event_id INT NOT NULL,
 user_id INT NOT NULL,
 status TINYINT NOT NULL,
 PRIMARY KEY (event_id, user_id)
);

Then it's easy to register a new member of the event:

INSERT INTO pu_event_members SET event_id=?, user_id=?, status=?

Or update their status:

UPDATE pu_event_members SET status=? WHERE event_id=? AND user_id=?

Working example but only select:

select pu_events.*
from pu_events, JSON_TABLE(members, "$.members[*].uid" COLUMNS(f INT PATH '$')) as list
where list.f = 1

Mysql 8 has support JSON_TABLE

https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html https://dev.mysql.com/doc/refman/8.0/en/json-table-functions.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM