【发布时间】:2019-04-11 11:46:15
【问题描述】:
我有一个accounts 表和一个account_logins 表。我正在尝试选择每个帐户,然后按上次登录时间对其进行排序。到目前为止,我有以下内容:
accounts
.confirmed_visible_with_completed_profile
.joins(:logins)
.select('accounts.*, max(account_logins.created_at) as last_sign_in_at')
.group('accounts.id')
但是,如果一个帐户没有与之关联的 account_logins,则此方法有效,则不会在查询中返回。我的 SQL 很差,但我通过谷歌搜索找到了 COALESCE,并尝试过:
accounts
.confirmed_visible_with_completed_profile
.joins(:logins)
.select('accounts.*, COALESCE(max(account_logins.created_at), 0) as last_sign_in_at')
.group('accounts.id')
但是,这仍然不会返回没有关联 account_login 的记录。从我读到的COALESCE(max(account_logins.created_at), 0) 应该返回 0 如果 max(account_logins.created_at) 为 NULL,所以我很困惑为什么这不起作用。非常感谢任何帮助
【问题讨论】:
标签: mysql sql ruby-on-rails ruby