在下面的查詢中,我們將根據「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)
這是PostgreSQL的。我猜上述查詢不會工作,因爲property_moveout_interval對於所有屬性都不相同。 –