【问题标题】:ActiveRecord count distinct when joining tables连接表时 ActiveRecord 计数不同
【发布时间】:2017-01-12 08:18:15
【问题描述】:

我正在尝试创建一个 ActiveRecord 查询,该查询计算所有events,其中position = move_left 用于特定用户,当statusmovedmoved_correct 时加入statuses。我正在努力解决的问题是,我的events 可能有多个记录具有特定用户的相同数据,因为它们是事件并且您可以多次执行相同的事件。

我的两个模型:

事件:

belongs_to :user
belongs_to :status

状态:

belongs_to :user
has_many :events

由于有多个用户,我需要为每个特定用户获取最后创建的event,并加入statuses,其中statuses.positionmovedmoved_correct

SELECT  `events`.* FROM `events` ORDER BY `events`.`id` DESC

=> <Event id: 1, user_id: 1, position: "move_left">
=> <Event id: 2, user_id: 1, position: "right">
=> <Event id: 3, user_id: 1, position: "move_left">

=> <Event id: 4, user_id: 2, position: "move_left">
=> <Event id: 5, user_id: 2, position: "right">
=> <Event id: 6, user_id: 3, position: "right">

..

SELECT  `statuses`.* FROM `statuses` ORDER BY `statuses`.`id` DESC

=> <Status id: 1, status_now: "moved", user_id: 1>
=> <Status id: 2, status_now: "moved_correct", user_id: 1>

=> <Status id: 3, status_now: "moved", user_id: 2>
=> <Status id: 4, status_now: "moved_correct", user_id: 3>
=> <Status id: 5, status_now: "moved_down", user_id: 3>

使用该样本数据,我希望看到的总数为 4(user_id: 1 返回 2,user_id: 2 返回 1,user_id: 3 返回 1)

这是一个关于我如何描绘它的示例查询,但我不确定我哪里出错了。任何帮助将不胜感激!

Event.select(:user_id).distinct.order(id: :desc).first.joins("JOIN statuses ON events.user_id = statuses.user_id AND 
statuses.status_now IN ('moved', 'moved_correct')").count

【问题讨论】:

    标签: mysql ruby-on-rails ruby activerecord


    【解决方案1】:

    根据我对您给定场景的假设,试试这个:

    Event.joins(:user).joins(:status)
    .where("statuses.status_now IN ('moved', 'moved_correct') AND events.position = 'move_left')"
    .distinct.count("events.id")
    

    【讨论】:

    • 这似乎无法正常工作。为了澄清我正在寻找更多类似的东西:SELECT DISTINCT COUNT(DISTINCT statuses.id) FROM events INNER JOIN statuses ON statuses.user_id = activity_events.user_id WHERE (statuses.status_now IN ('moved', 'moved_correct') AND events.position = 'move_left') - 但基于最后一个唯一的 events.user_id 计数为 statuses
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-16
    • 2015-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多