我有两个表ITEMS和ITEM_AUDITS。一个项目可以有0个或更多与之关联的审计记录。字段和查找需要资源和状态。
我正在尝试创建一个查询,计算两个表中item_id的出现次数。有效地生成类似于以下示例的数据
Title Item_ID Count
ABC 1 2
ABC 3 4
Bible 5 1
我已经能够创建一个联合查询,生成没有计数的数据:
# Declare Arel objects
i = Item.arel_table
ia = ItemAudit.arel_table
s = Status.arel_table
r = Resource.arel_table
######################
# Build the item query
######################
# Build the joins
item = Item.joins(
i.join(r, Arel::Nodes::OuterJoin).on(i[:resource_id].eq(r[:id]))
.join(s, Arel::Nodes::OuterJoin).on(i[:status_id].eq(s[:id]))
.join_sql
).uniq
# Build the select columns
#item = item.select('resources.title, items.id as id, count(*) as loan_count')
item = item.select('resources.title, items.id as item_id')
# Adds the where criteria
item = item.where(
s[:title].matches("On Loan").or(s[:title].matches("Permanent Loan"))
)
# Add the group by clause
item = item.group("items.id")
##########################
# Build item history query
##########################
# Build the joins
item_audit = Item.joins(
i.join(ia).on(i[:id].eq(ia[:item_id]))
.join(r, Arel::Nodes::OuterJoin).on(i[:resource_id].eq(r[:id]))
.join(s, Arel::Nodes::OuterJoin).on(i[:status_id].eq(s[:id]))
.join_sql
)
# Build the select columns
item_audit = item_audit.select('resources.title, item_audits.item_id as item_id')
#######################
# Union the two queries
#######################
report = item.union(:all, item_audit).select('title, item_id')
我无法超越这个以获得类似
的计数report = item.union(:all, item_audit).select('title, item_id, count(item_id)')
修改
我试图最终得到的SQL如下(一个简单的组并计算联合结果)。
select qry.title, qry.item_id, count(qry.item_id) from(
SELECT DISTINCT
resources.title, items.id as item_id
FROM
`items`
LEFT OUTER JOIN
`resources` ON `items`.`resource_id` = `resources`.`id`
LEFT OUTER JOIN
`statuses` ON `items`.`status_id` = `statuses`.`id`
WHERE
((`statuses`.`title` LIKE 'On Loan'
OR `statuses`.`title` LIKE 'Permanent Loan'))
GROUP BY items.id
UNION ALL SELECT
resources.title, item_audits.item_id as item_id
FROM
`items`
INNER JOIN
`item_audits` ON `items`.`id` = `item_audits`.`item_id`
LEFT OUTER JOIN
`resources` ON `items`.`resource_id` = `resources`.`id`
LEFT OUTER JOIN
`statuses` ON `items`.`status_id` = `statuses`.`id`) as qry
group by qry.item_id
任何人都给我任何指示。
非常感谢,