5

我试图让一个简单的数据库查询正常工作,但我无法clojure/java.jdbcIN子句中进行选择。

代码如下所示:

(sql/with-connection db
  (sql/with-query-results rows
    ["select  f.name        name
          ,   f.id          file_id
      from    FileCategory  fc
      join    File          f
          on  fc.file       = f.id
      where   fc.category   in ?
      having  count(1)      >= ?"
     [1 2]    ; This is the bit which does not work.
              ; I have tried (to-array) and (set) too
     2]
    (into [] rows)))

关于如何将集合传递给查询的任何想法?

直接在下面运行查询mysql我没有问题:

mysql> select f.name, f.id from FileCategory fc join File f on fc.file = f.id where fc.category in (1, 2) having count(1) >= 2;
+-----------+----+
| name      | id |
+-----------+----+
| some name |  1 |
+-----------+----+
1 row in set (0.02 sec)

mysql> 

如果它有所不同,我正在使用:org.clojure/clojure 1.4.0、org.clojure/java.jdbc 0.2.3 和 mysql/mysql-connector-java 5.1.6。

4

2 回答 2

0

如果您使用 SQL,您必须生成一个带有正确数量的“?”的 SQL 查询。很遗憾。

您可能会发现在更高的抽象级别上工作会更好。例如。您在korma中的查询如下所示:

(defentity file)
(defentity filecategory)

(def categories ["movie" "tv" "news"])

(as-sql (select file
       (fields :name :file_id)
       (join filecategory (= :file.id :filecategory.file))
           (where { :filecategory.category [in categories]} )
       (having (> (sqlfn :count 1) 1))))

; SELECT `file`.`name`, `file`.`file_id` FROM `file` LEFT JOIN 
;        `filecategory` ON `file`.`id` = `filecategory`.`file` 
;         WHERE (`filecategory`.`category` IN (?, ?, ?)) 
;         HAVING COUNT(?) > ?  ::  [tv movie news 1 1]    

defentity如果需要,您可以通过将 FK 声明移动到调用中来进一步整理。

于 2013-03-23T07:49:55.910 回答
0

尝试这个:

(sql/with-connection db
  (sql/with-query-results rows
    ["select  f.name        name
          ,   f.id          file_id
      from    FileCategory  fc
      join    File          f
          on  fc.file       = f.id
      where   fc.category   in (?, ?)
      having  count(1)      >= ?"
     1 2 2]
    (into [] rows)))
于 2013-03-22T21:59:51.260 回答