SqlKoram - 加入子选择但如何指定别名?

时间:2018-05-31 10:57:31

标签: clojure korma sqlkorma

我想在此查询中为子选择分配别名:

(->
  (korma/select* table_a)
  (korma/join
      (korma/subselect table_b
                       (korma/fields :id (korma/raw "COUNT(*) AS count"))
                       (korma/group :id)
   (= :id :id))

这是我想要创建的SQL:

SELECT * FROM table_a LEFT JOIN (SELECT id, COUNT(*) AS count FROM table_b GROUP BY id) AS b b.id = id;

但是目前sql korma刚刚生成:

SELECT * FROM table_a LEFT JOIN (SELECT id, COUNT(*) AS count FROM table_b GROUP BY id) id = id;

1 个答案:

答案 0 :(得分:0)

我需要将子选择定义为单独的实体,见下文:

(korma/defentity sub-select
             (korma/table (korma/subselect table_b
                                           (korma/fields :id(korma/raw "COUNT(*) AS count"))
                                           (korma/group :id)) :b))

(->
  (korma/select* table_a)
  (korma/join sub-select (= :b.id :id)))

生成以下查询:

SELECT * FROM table_a LEFT JOIN (SELECT id, COUNT(*) AS count FROM table_b GROUP BY id) a.id = id;