[英]Rails - SQL - joins and COALESCE
我有一个帐户表和一个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)
如果max(account_logins.created_at)为NULL,则COALESCE(max(account_logins.created_at), 0)
应该返回0,所以我很困惑为什么这不起作用。 任何帮助深表感谢
您错过了连接部分中的那些值,因此在这种情况下, select
coalesce
是无用的。 select
是最后应用的操作。 您需要left join
来解决您的问题
在rails 5中,您有left_joins
accounts
.confirmed_visible_with_completed_profile
.left_joins(:logins)
.select('accounts.*, COALESCE(max(account_logins.created_at), 0) as last_sign_in_at')
.group('accounts.id')
前轨5
accounts
.confirmed_visible_with_completed_profile
.joins("LEFT JOIN account_logins ON accounts.id = account_logins.account_id")
.select('accounts.*, COALESCE(max(account_logins.created_at), 0) as last_sign_in_at')
.group('accounts.id')
您仍然需要coalesce
。 left join
很有意义
尝试使用nullif
COALESCE(nullif(max(account_logins.created_at),''), 0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.