2013-03-22 55 views
4

我想獲得一個簡單的數據庫查詢工作,但我不能得到clojure/java.jdbcIN子句中進行選擇。如何使用clojure/java.jdbc中的「WHERE x IN y」子句?

的代碼看起來是這樣的:

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

+0

你不能用準備好的語句來做到這一點。那麼,你可以使用WHERE(?,?)HAVING count(1)> =?'和'1 2 2'作爲數據參數。但不是這樣。 – Esailija 2013-03-22 21:53:49

回答

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))) 
+0

不幸的是,列表中的項目數量是可變的。第二個參數是計數。 – dsm 2013-03-22 22:02:22

+0

@dsm我看到了,你需要在字符串中動態創建適量的'?',然後 – Esailija 2013-03-22 22:03:19

+0

是的。我希望它不會那樣。 – dsm 2013-03-22 22:07:17

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調用進一步整理這件事。