1

我有一个简单的 SQL 图形数据库。

数据库:

CREATE TABLE Person (
  ID INTEGER PRIMARY KEY,
  name VARCHAR(100)
) AS NODE;

CREATE TABLE City (
  ID INTEGER PRIMARY KEY,
  name VARCHAR(100)
) AS NODE;

CREATE TABLE Travels AS EDGE;

INSERT INTO Person VALUES (3,'Cecil');
INSERT INTO Person VALUES (4,'Diane');
INSERT INTO Person VALUES (2,'Bob');
INSERT INTO Person VALUES (1,'Alice');

Insert into City VALUES (1, 'Almaty')
Insert into City VALUES (2, 'Bangkok')
Insert into City VALUES (3, 'Casablanca')
Insert into City VALUES (4, 'Dublin')


INSERT INTO Travels VALUES ((SELECT $node_id FROM Person WHERE ID = 1),
      (SELECT $node_id FROM City WHERE ID = 1));
INSERT INTO Travels VALUES ((SELECT $node_id FROM Person WHERE ID = 2),
      (SELECT $node_id FROM City WHERE ID = 2));
INSERT INTO Travels VALUES ((SELECT $node_id FROM Person WHERE ID = 3),
      (SELECT $node_id FROM City WHERE ID = 3));
INSERT INTO Travels VALUES ((SELECT $node_id FROM Person WHERE ID = 4),
      (SELECT $node_id FROM City WHERE ID = 4));

我想将这些表复制到不同的表中。我的目标是在 C# 中实现它,但简单的 TSQL 解决方案就足够了。

CREATE TABLE Person2 (
  ID INTEGER PRIMARY KEY,
  name VARCHAR(100)
) AS NODE;

CREATE TABLE City2 (
  ID INTEGER PRIMARY KEY,
  name VARCHAR(100)
) AS NODE;

CREATE TABLE Travels2 AS EDGE;

如果我只读取用户数据而不是内部列 $node_id,我可以轻松地从节点表中复制数据:

insert into Person2(ID, name) (select Id, name from Person)
insert into City2(ID, name) (select id, name from City)

但在旅行表中,我只有以下信息:

select $edge_id, $from_id, $to_id from Travels :

{"type":"edge","schema":"dbo","table":"Travels","id":0} {"type":"node","schema":"dbo","table":"Person","id":3}  {"type":"node","schema":"dbo","table":"City","id":0}

为了复制它,我需要在表 Person、City、Travels 上创建一个连接以获取原始 IDS,然后将其与 Person2 和 City2 连接以获取 Travels2 的新值 $from_id、$to_id

另一种选择是使用函数 Graph_ID_FROM_NODE_ID 和 NODE_ID_FROM_PARTS:

insert into Person2($node_id, ID, name) 
    (select ''+NODE_ID_FROM_PARTS(OBJECT_ID('dbo.Person2'),Graph_ID_FROM_NODE_ID($node_id)), Id, name from Person )

insert into City2($node_id, ID, name)
    (select ''+NODE_ID_FROM_PARTS(OBJECT_ID('dbo.City2'),Graph_ID_FROM_NODE_ID($node_id)), Id, name from City ) 

Insert into Travels2 ($edge_id, $from_id, $to_id) 
(select ''+EDGE_ID_FROM_PARTS(OBJECT_ID('dbo.Travels2'), Graph_ID_FROM_EDGE_ID($edge_id)), ''+NODE_ID_FROM_PARTS(OBJECT_ID('dbo.Person2'),Graph_ID_FROM_NODE_ID($from_id)), ''+NODE_ID_FROM_PARTS(OBJECT_ID('dbo.City2'),Graph_ID_FROM_NODE_ID($to_id)) from Travels
) 

可能,我不需要复制边的 id,所以最后一次插入会更容易一些,但我想知道,如果没有更简单的方法来复制图表。

4

0 回答 0