Java SQL:使用以前存在的结果集

时间:2016-05-25 14:51:14

标签: java sql postgresql caching views

我无法在其他地方找到答案,所以我现在就问这个。

我使用嵌入式PostgreSQL和java.sql来执行Java查询。

我有一个我想执行的查询,如下所示:

PreparedStatement ps = connection.prepareStatement(PreparedStatement ps = connection.prepareStatement("DELETE FROM table1 WHERE table2id in cachedTable1" + 
                        "AND table3id in " +
                        "(SELECT id FROM table3 WHERE string2 = ?) " +
                        "AND (table3id, table2id) NOT IN " +
                        "(SELECT table3id, table2id " +
                        "FROM table1 " +
                        "WHERE table2id in " +
                        "(SELECT id FROM table2 WHERE string1 = ?) " +
                        "AND table3id in " +
                        "(SELECT id FROM table3 WHERE string2 = ?) LIMIT 1)"))

但是,我最终要做的是执行这些嵌套查询两次:

(SELECT id FROM table2 WHERE string1 = ?) 

...和...

(SELECT id FROM table3 WHERE string2 = ?)

我想要做的只是执行一次。例如,我想将这些查询存储在两个不同的结果集中,并且能够在我的查询中引用它们,如下所示:

 PreparedStatement ps = connection.prepareStatement(PreparedStatement ps = connection.prepareStatement("DELETE FROM table1 WHERE table2id in cachedTable1" + 
                            "AND table3id in " +
                            "cachedTable2 " +
                            "AND (table3id, table2id) NOT IN " +
                            "(SELECT table3id, table2id " +
                            "FROM table1 " +
                            "WHERE table2id in " +
                            "cachedTable1 " +
                            "AND table3id in " +
                            "cachedTable2 LIMIT 1)"))

...我们可以假设第一个嵌套查询的结果存储在cachedTable1中,第二个查询的结果存储在cachedTable2中。

我简要地略过了一些答案,有些人似乎暗示我不能在Native Java中做这样的事情,并且在本机Java中也不能支持这些视图。有没有办法实现这个查询缓存?

1 个答案:

答案 0 :(得分:0)

我会尝试将with子句(也称为CTE)与PerparedStatement一起使用:

WITH table3_ids AS (SELECT id FROM table3 WHERE string2 = ?)
DELETE FROM table1
WHERE
    table2id in cachedTable1
    AND table3id in table3_ids
    AND (table3id, table2id) NOT IN 
        (SELECT table3id, table2id 
         FROM table1 
         WHERE table2id in 
         (SELECT id FROM table2 WHERE string1 = ?) 
    AND table3id in  table3_ids
LIMIT 1)

就我可以在网上查找一样,CTE with子句充当临时表。尽管如此,试验一下会很好。