我一直在尝试在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在引擎盖下使用预先准备,它仅适用于单个语句,还为您准备。
这有效:
;; 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)))
但是,即使从这个小例子中很难看出,我也对您的命名/模式有些困惑。您的功能称为"儿童",但使用()我认为它将返回最大记录。另外,它似乎选择了 parent ,但是随着隐式加入,它总是会选择自己?
如果post_map是从id到parent_id的链接,并且您想让孩子们,我会认为更多的是:
(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}))]}))))