简短版本:如何在 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是一个为模型添加简单标记的 gem。它添加了一个方法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 来表达吗?