我假設事件包含期間關聯?
在任何情況下,您都想要在折扣表和句點表之間進行左連接。這將爲您提供執行begin = today
where子句的時間段數據,如果沒有時間段,則爲null。因此,選擇數據的SQL將
SELECT [columns]
FROM discounts_table
LEFT JOIN periods_table ON periods_table.discount_id = discounts_table.id
WHERE (periods_table.begin = [today]) OR (periods_table.begin IS NULL AND discounts_table.created_at BETWEEN [yesterday] AND [today])
在鐵軌你應該能夠做到這一點,如下所示:
Discount
.joins("LEFT JOIN periods_table ON periods_table.discount_id = discounts_table.id")
.where("(periods_table.begin = ?) OR (periods_table.begin IS NULL AND discounts_table.created_at BETWEEN ? AND ?)", today, today, 1.day.ago.to_date)
不幸的是,你需要使用SQL語句,而不是讓軌道爲您創建它如:
- 與符號的連接只創建一個INNER JOIN,而不是一個LEFT JOIN
- 其中的符號,哈希等將結合C^onditions使用AND,而不是OR
謝謝,它的工作原理。我注意到的一件事是它很慢(4000個折扣/ 8000個週期,都有索引)。我想一旦我將其他示波器混合在一起,它就會好起來的。 – lulalala 2012-04-05 10:26:15