Assume we have systems, subsystems and devices. Each of them are in 0..* relationship. Here are the tables (properties are not displayed, for simplification)
CREATE TABLE system( sid INT NOT NULL AUTO_INCREMENT, sysident VARCHAR(80) NOT NULL, //... cid INT NOT NULL, //Foreign Key to Customer PRIMARY KEY(sid)); CREATE TABLE subsystem( subsid INT NOT NULL AUTO_INCREMENT,//... subsident INT NOT NULL, sid INT NOT NULL, //systems foreign key PRIMARY KEY(subsid)); CREATE TABLE device( did INT NOT NULL AUTO_INCREMENT,//... dident INT NOT NULL, subsid INT NOT NULL, //subsystems foreign key PRIMARY KEY(did)); Now assume there's a interface where sb can upload data. Data is structured (JSON) like this
{ "systemname": "testsystem", //system.systemname "deviceinfos": [ { "id": "2-90" //"subsystem.subsystemident-device.deviceident" }] } Task is to insert or update the data in the tables. (maybe some metadata changed for the device testsystem-2-90 (this ident is not unique in the tables).
Approach is :
INSERT INTO system(sid, sysident, cid) VALUES ( (SELECT sid FROM (SELECT DISTINCT sid FROM user JOIN customer on user.cid = customer.cid JOIN system ON system.cid = customer.cid WHERE customer.cid = 1 and system.sbid = 1 as a), 'systemsname', 1) ) ON DUPLICATE KEY UPDATE // some metainfo Is there a way to make this simpler? For system, its no problem to insert/update this properly. But for subsystems and devices its getting huge and I'm cautious about the approach.
Any advice?