2013-11-21 64 views
0

在下面的查詢中,我們將根據「property_id」在「move_out_date」上添加天數。加入以下SQL查詢的替代

我們已經寫下面的查詢,它工作正常。

但問題是,如果有N個,我們需要使用加入了N次(在下面情況下,只有2個屬性)的屬性數量。

有沒有更好的和優化的方法來完成它?

SELECT 
    * 
FROM 
    leases l 
    JOIN lease_processes lp ON (lp.management_company_id = l.management_company_id AND lp.lease_id = l.id AND lp.customer_id IS NULL) 
    JOIN lease_customers lc ON (lc.management_company_id = l.management_company_id AND lc.lease_id = l.id AND lc.customer_id = l.primary_customer_id) 
WHERE 
    l.management_company_id = 2636 
    AND lp.fmo_processed_on IS NULL 
    AND lc.lease_status_type_id = 6 
    AND (lp.move_out_date + INTERVAL '5 day' <= date(NOW()) AND l.property_id = 28949) 

UNION 

SELECT 
    * 
FROM 
    leases l 
    JOIN lease_processes lp ON (lp.management_company_id = l.management_company_id AND lp.lease_id = l.id AND lp.customer_id IS NULL) 
    JOIN lease_customers lc ON (lc.management_company_id = l.management_company_id AND lc.lease_id = l.id AND lc.customer_id = l.primary_customer_id) 
WHERE 
    l.management_company_id = 2636 
    AND lp.fmo_processed_on IS NULL 
    AND lc.lease_status_type_id = 6 
    AND (lp.move_out_date + INTERVAL '1 day' <= date(NOW()) AND l.property_id = 28098) 

回答

0

您可能想要考慮編輯您的標籤,以便我們可以真實地告訴您的環境是什麼。

除非我錯過了一些你沒有觸及連接條件,只是改變where子句。情況就是這樣,你可以使用像CASE這樣的適當的條件或更適當的方法,你可以將文字間隔值('1 day'等)保存到相關屬性的租約表記錄的屬性中,然後過濾一次計算值。

SELECT 
    * 
FROM 
    leases l 
    JOIN lease_processes lp ON (lp.management_company_id = l.management_company_id AND lp.lease_id = l.id AND lp.customer_id IS NULL) 
    JOIN lease_customers lc ON (lc.management_company_id = l.management_company_id AND lc.lease_id = l.id AND lc.customer_id = l.primary_customer_id) 
WHERE 
    l.management_company_id = 2636 
    AND lp.fmo_processed_on IS NULL 
    AND lc.lease_status_type_id = 6 
    AND (lp.move_out_date + l.property_moveout_interval <= date(NOW()) 
AND l.property_id in var_some_aggregated_ID_list) 
+0

這是PostgreSQL的。我猜上述查詢不會工作,因爲property_moveout_interval對於所有屬性都不相同。 –

1
SELECT 
    * 
FROM 
    leases l 
    JOIN lease_processes lp ON (lp.management_company_id = l.management_company_id AND lp.lease_id = l.id AND lp.customer_id IS NULL) 
    JOIN lease_customers lc ON (lc.management_company_id = l.management_company_id AND lc.lease_id = l.id AND lc.customer_id = l.primary_customer_id) 
WHERE 
    l.management_company_id = 2636 
    AND lp.fmo_processed_on IS NULL 
    AND lc.lease_status_type_id = 6 
    AND ((lp.move_out_date + INTERVAL '5 day' <= date(NOW())) OR (lp.move_out_date + INTERVAL '1 day' <= date(NOW()))) 
    AND l.property_id = 28949