我必须做这样的事情
insert into object (name, value, first_node) values ('some_name', 123, 0)
@id = mysql_last_insert_id()
insert nodes (name, object_id) values ('node_name',@id)
@id2 = mysql_last_insert_id()
update object set first_node=@id2 where id=@id
是否可以使其更简单? 如果我想插入更多具有合理效率的对(对象,节点),该怎么办?
答案 0 :(得分:0)
您应该使用第三个表来建立关系:
您可以这样进行插入:
insert into object (name, value) values ('some_name', 123)
@oid = mysql_last_insert_id()
insert nodes (name) values ('node_name')
@nid = mysql_last_insert_id()
insert obj_node (node,object) values (@nid, @oid)
然后,您可以使用连接来获取特定对象(或节点的对象)的节点:
SELECT O.ID AS OID, O.NAME AS ONAME, O.VALUE, N.NAME AS NNAME, N.ID AS NID
FROM OBJECT AS O
JOIN OBJ_NOD ON OBJ_NOD.OBJECT = O.ID
JOIN NODES AS N ON N.ID = OBJ_NOD.NODE
WHERE O.ID = @object_id; —- or 'N.ID = @node_id' if you want to get elements from a node id