[英]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.