你如何在clojure / java.jdbc中使用“WHERE x IN y”子句?

时间:2013-03-22 21:46:13

标签: mysql jdbc clojure

我正在尝试使用简单的数据库查询,但我无法从clojure/java.jdbc子句中选择IN

代码如下所示:

(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。

2 个答案:

答案 0 :(得分: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)))

答案 1 :(得分: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]    

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