gpt4 book ai didi

postgresql - 使用 Clojure/Korma/Postgres 的带有子选择的准备好的语句

转载 作者:行者123 更新时间:2023-11-29 13:05:46 27 4
gpt4 key购买 nike

我一直尝试在 Korma 中执行以下操作但无济于事:

sql:

PREPARE q (int) AS SELECT * FROM post a
WHERE EXISTS
(SELECT parent_id
FROM post_map
WHERE parent_id=a.id AND parent_id=$1);
EXECUTE q(1);

我最好的 Korma 尝试:

(defn children [parent-id]        ;; clojure
(if (number? parent-id)
(exec-raw (str
"PREPARE q (int) AS SELECT * FROM post a WHERE EXISTS
(SELECT parent_id FROM post_map WHERE parent_id=a.id AND parent_id=$1);
EXECUTE q(" parent-id ")")
:results)))

这是我不断收到的错误: (我不太理解下面的 :: 运算符:)

Failure to execute query with SQL:
PREPARE q (int) AS SELECT * FROM post a WHERE EXISTS
(SELECT parent_id FROM post_map WHERE parent_id=a.id AND parent_id=$1);
EXECUTE q(1) :: nil
PSQLException:
Message: No results were returned by the query.
SQLState: 02000
Error Code: 0
PSQLException No results were returned by the query. org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery (AbstractJdbc2Statement.java:274)

我认为用查询来做这件事并不奇怪,所以我想知道 Korma 是否不适合我的项目。我只是做错了吗?

更新:这就是我最终所做的(在我放弃 Korma [抱歉 Korma] 之后)。

(defn children [parent-id]
(if (unsigned? parent-id)
(sql/with-connection db
(sql/with-query-results results
[(str "select " field-list ", b.parent_id from post a, post_map b where a.id=b.child_id and a.id in "
"(select child_id from post c, post_map d where c.id=d.parent_id and c.id=?)") parent-id]
(into [] results)))))

最佳答案

Korma 在幕后使用 do-prepared,它只对单个语句有效,同时也会为你准备好它。

这个有效:

;; but isn't it more 'parent' than 'children'?
(defn children-raw [parent-id]
(if (number? parent-id)
(exec-raw [(str
"SELECT * FROM post a WHERE EXISTS
(SELECT parent_id FROM post_map WHERE parent_id=a.id AND parent_id=?)")
[parent-id]]
:results)))

尽管从这个小示例中很难分辨,但我对您的命名/架构感到有些困惑。您的函数称为“childREN”,但使用 EXISTS() 我认为它最多会返回一条记录。此外,它似乎选择了父级,但是通过隐式连接它总是会选择自己?

如果 post_map 是从 id 到 parent_id 的链接,并且您想得到 child ,我会考虑更多:

(defentity post
(entity-fields :id))
(defentity post_map
(entity-fields :id :parent_id))
(defn children-dsl [parent-id]
(if (number? parent-id)
(select post
(where {:id [in (subselect post_map
(fields :id)
(where {:parent_id parent-id}))]}))))

关于postgresql - 使用 Clojure/Korma/Postgres 的带有子选择的准备好的语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13097697/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com