2013-08-23 59 views
2

我有一個Postgres表,其中用戶可以有多個付款訂閱,付款訂閱可以是活動的或非活動的,這通過支付訂閱表上的activated_at和inactivated_at日期字段來顯示。我現在想找到沒有活動付款訂閱的所有用戶。獨家加盟有很多關係

找到所有的用戶,無需任何付款訂閱是很容易的

User.joins("LEFT JOIN payment_subscriptions ON (payment_subscriptions.user_id = users.id)").where("payment_subscriptions.id IS NULL") 

我也想找到所有誰只有不活動的訂閱用戶。如果我使用與上述相同的模式,我會找到所有在某個時間點已停用其訂閱的用戶,但不能保證他們也沒有活動訂閱。

User.joins("LEFT JOIN payment_subscriptions ON (payment_subscriptions.user_id = users.id)").where("payment_subscriptions.inactivated_at IS NOT NULL") 

如何從我的表中獲取沒有訂閱或沒有活動訂閱的用戶?

回答

2

這個給你沒有任何活動訂閱的用戶。

User.joins("LEFT JOIN payment_subscriptions on (payment_subscriptions.user_id = users.id and payment_subscriptions.inactivated_at is null)").where("payment_subscriptions.id is null") 

如果你想只有那些誰都有不活躍,也使用以前加入

我不知道,如果它的軌道可能的,但你也可以使用not exists語法:

User.where(' 
    not exists (
     select * 
     from payment_subscriptions as ps 
     where ps.user_id = users.id and ps.inactivated_at is not null 
    ) 
') 
0

如果用戶目前沒有訂閱付款,您尚未提供有關如何實際定義的信息,但根據我推斷您需要檢查的是payment_subscriptions.inactivated_at不爲null,並且payment_subscriptions.id爲也是空的。

User.joins("LEFT JOIN payment_subscriptions ON (payment_subscriptions.user_id = users.id)").where("payment_subscriptions.inactivated_at IS NOT NULL AND payment_subscriptions.id IS NULL") 
+0

這實際上會給我所有的用戶誰沒有訂閱或在某個點上已經停用訂閱。由於用戶可以有多個訂閱,所以他們很可能擁有活動訂閱以及不活動的訂閱。 –