短版本:如何在squeel中編寫此查詢?squeel中的嵌套查詢
SELECT OneTable.*, my_count
FROM OneTable JOIN (
SELECT DISTINCT one_id, count(*) AS my_count
FROM AnotherTable
GROUP BY one_id
) counts
ON OneTable.id=counts.one_id
龍版本:rocket_tag是,增加了簡單的標籤,以模型的瑰寶。它增加了一個方法tagged_with
。假設我的模型是User
,帶有一個ID和名稱,我可以調用User.tagged_with ['admin','sales']
。在內部它使用此squeel代碼:
select{count(~id).as(tags_count)}
.select("#{self.table_name}.*").
joins{tags}.
where{tags.name.in(my{tags_list})}.
group{~id}
生成此查詢:
SELECT count(users.id) AS tags_count, users.*
FROM users INNER JOIN taggings
ON taggings.taggable_id = users.id
AND taggings.taggable_type = 'User'
INNER JOIN tags
ON tags.id = taggings.tag_id
WHERE tags.name IN ('admin','sales')
GROUP BY users.id
一些的RDBMS是否喜歡這個,但Postgres的抱怨:
ERROR: column "users.name" must appear in the GROUP BY
clause or be used in an aggregate function
我相信一個比較認同的方式編寫查詢將是:
SELECT users.*, tags_count FROM users INNER JOIN (
SELECT DISTINCT taggable_id, count(*) AS tags_count
FROM taggings INNER JOIN tags
ON tags.id = taggings.tag_id
WHERE tags.name IN ('admin','sales')
GROUP BY taggable_id
) tag_counts
ON users.id = tag_counts.taggable_id
有什麼方法可以用squeel來表達這個嗎?
你是什麼PostgreSQL版本? – 2012-03-19 07:22:09