简体   繁体   English

左外部连接在导轨中

[英]Left outer join in rails

I have two objects - Customers & Customer Checkins. 我有两个对象-客户和客户签到。 Each customer has many checkins and each checkin belongs to one customer. 每个客户都有许多签到,每个签到属于一个客户。

I need to come up with a query that outputs the complete list of customers together with their checkin count per month. 我需要提出一个查询,该查询输出完整的客户列表以及每月的签到计数。 My current query is shown below: 我当前的查询如下所示:

customer = Customer.where(account_id: 139).joins('LEFT JOIN
    customer_checkins on customer_checkins.customer_id =
    customers.id').uniq.select("COUNT(*) as count, customers.created_at as
    created_at, customers.name, customers.telephone, customers.mobile,
    customers.email, customers.gender, customers.city,
    customers.birthday,date_format(customer_checkins.created_at, '%b') as
    'month', customers.id").group("customer_checkins.customer_id,
    date_format(customer_checkins.created_at, '%b %Y')")

This query does not list all the customers. 此查询未列出所有客户。 What is wrong with my code? 我的代码有什么问题?

It does not list all the customers because you're only searching for ones with account_id: 139. 它不会列出所有客户,因为您仅在搜索具有account_id:139的客户。

Replace 更换

customer = Customer.where(account_id: 139)...

With

 customer = Customer...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM