如何优化INSERT到链接表

时间:2016-04-22 15:32:35

标签: java sql database derby

任何人都可以推荐更好的SQL语句或方法,以便我能更快地INSERT INTO链接表吗?随着表格变大,我的当前方法变慢,我的链接表INSERT查询就成了问题。

我有两个由链接表连接的表。架构如下:

CREATE TABLE table1
(id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
field1 VARCHAR(40))

CREATE TABLE table2
(id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
field1 VARCHAR(100),
field2 INT,
field3 VARCHAR(40))

CREATE TABLE linkTable
(id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
field1 INT REFERENCES table1(id),
field2 INT REFERENCES table2(id))

因为我正在尝试批量插入,我目前正在检查我是否在链接表中使用此长查询添加重复值:

INSERT INTO linktable(field1,field2)
SELECT table1Id, table2Id FROM
(SELECT table1.id table1Id, table2.id table2Id FROM table1,table2
WHERE table1.name=? AND table2.name=?) tmp
WHERE NOT EXISTS
(SELECT linktable.field1 FROM linktable tmp1 WHERE
tmp1.field1=tmp.table1id AND tmp1.field2=tmp.table2id)

1 个答案:

答案 0 :(得分:0)

如果您使用java来插入它,您可以使用ResultSet来检查列中某些内容的计数,然后在该计数等于零时插入,如此。

ResultSet = Statement.executeQuery ("Select count     (column_name) From table_name Where column_name = 'whatever';

While (rs.next ()){
 Int count = rs.getInt (count (column_name);

 If (count == 0){
         Statement2.executeUpdate ("INSERT INTO......")

  } 


   }