我目前有一个相当简单的数据库,由脚本定期更新。我想通过比较2列的相等性来过滤结果。 SQL查询看起来像:
SELECT devices.site_name, devices.device_name, devices.created_at FROM devices, locations WHERE devices.created_at = locations.most_recent_updated_time AND devices.site_name = locations.site_name;
这是我的datamapper模型
class Device
include DataMapper::Resource
property :id, Serial
property :device_name, Text, :required => true
property :site_name, Text, :required => true
property :created_at, DateTime
belongs_to :location
end
class Location
include DataMapper::Resource
property :site_name, Text, :required => true, :key => true
property :most_recent_updated_time, DateTime, :required => true
has n, :devices
end
每次脚本运行时,它都会附加新的Device条目并更新Location表中的`:most_recent_updated_time字段。以下是表格更新方式的示例。
Devices ╔════╦═════════════╦═══════════╦═══════════════════════════╗ ║ ID ║ Device_Name ║ Site_Name ║ Created_at ║ ╠════╬═════════════╬═══════════╬═══════════════════════════╣ ║ 1 ║ Device1 ║ Dallas ║ 2013-07-23T16:59:12-04:00 ║ ║ 2 ║ Device2 ║ Dallas ║ 2013-07-23T16:59:12-04:00 ║ ║ 3 ║ Device3 ║ Chicago ║ 2013-07-23T16:59:12-04:00 ║ ╚════╩═════════════╩═══════════╩═══════════════════════════╝ Location ╔═══════════╦═══════════════════════════╗ ║ Site_Name ║ Most_Recent_Updated_Time ║ ╠═══════════╬═══════════════════════════╣ ║ Dallas ║ 2013-07-23T16:59:12-04:00 ║ ║ Chicago ║ 2013-07-23T16:59:12-04:00 ║ ║ Boston ║ 2013-07-23T16:59:12-04:00 ║ ╚═══════════╩═══════════════════════════╝
脚本运行后
Devices ╔════╦═════════════╦═══════════╦═══════════════════════════╗ ║ ID ║ Device_Name ║ Site_Name ║ Created_at ║ ╠════╬═════════════╬═══════════╬═══════════════════════════╣ ║ 1 ║ Device1 ║ Dallas ║ 2013-07-23T16:59:12-04:00 ║ ║ 2 ║ Device2 ║ Dallas ║ 2013-07-23T16:59:12-04:00 ║ ║ 3 ║ Device3 ║ Chicago ║ 2013-07-23T16:59:12-04:00 ║ ║ 4 ║ Device4 ║ Dallas ║ 2013-07-24T18:00:00-04:00 ║ ║ 5 ║ Device5 ║ Chicago ║ 2013-07-24T18:00:00-04:00 ║ ╚════╩═════════════╩═══════════╩═══════════════════════════╝ Location ╔═══════════╦═══════════════════════════╗ ║ Site_Name ║ Most_Recent_Updated_Time ║ ╠═══════════╬═══════════════════════════╣ ║ Dallas ║ 2013-07-24T18:00:00-04:00 ║ ║ Chicago ║ 2013-07-24T18:00:00-04:00 ║ ║ Boston ║ 2013-07-24T18:00:00-04:00 ║ ╚═══════════╩═══════════════════════════╝
因此,如果我在脚本运行后运行查询,我希望它返回Device4和Device5。
答案 0 :(得分:0)
如果我理解您的问题,请尝试将此方法添加到Location
:
def most_recent_devices
devices.all(:created_at => most_recent_updated_time)
end
然后你应该能够收集每个Location
的所有最新设备,如下所示:
Location.all.map(&:most_recent_devices).flatten