我目前有一个由脚本定期更新的相当简单的数据库。我想通过比较两列的相等性来过滤结果。SQL 查询如下所示:
选择 devices.site_name、devices.device_name、devices.created_at FROM 设备、位置 其中 devices.created_at = locations.most_recent_updated_time AND devices.site_name = locations.site_name;
这是我的数据映射器模型
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
每次脚本运行时,它都会附加新的设备条目并更新位置表中的 `:most_recent_updated_time 字段。这是如何更新表的示例。
设备 ╔════╦═════════════╦═══════════╦══════════════════ ═════════╗ ║ ID ║ Device_Name ║ Site_Name ║ Created_at ║ ╠════╬═════════════╬═══════════╬══════════════════ ═════════╣ ║ 1 ║ 设备 1 ║ 达拉斯 ║ 2013-07-23T16:59:12-04:00 ║ ║ 2 ║ 设备 2 ║ 达拉斯 ║ 2013-07-23T16:59:12-04:00 ║ ║ 3 ║ Device3 ║ 芝加哥 ║ 2013-07-23T16:59:12-04:00 ║ ╚════╩═════════════╩═══════════╩══════════════════ ═════════╝ 地点 ╔═══════════╦═══════════════════════════╗ ║ Site_Name ║ Most_Recent_Updated_Time ║ ╠═══════════╬═══════════════════════════╣ ║ 达拉斯 ║ 2013-07-23T16:59:12-04:00 ║ ║ 芝加哥 ║ 2013-07-23T16:59:12-04:00 ║ ║ 波士顿 ║ 2013-07-23T16:59:12-04:00 ║ ╚═══════════╩═══════════════════════════╝
脚本运行后
设备 ╔════╦═════════════╦═══════════╦══════════════════ ═════════╗ ║ ID ║ Device_Name ║ Site_Name ║ Created_at ║ ╠════╬═════════════╬═══════════╬══════════════════ ═════════╣ ║ 1 ║ 设备 1 ║ 达拉斯 ║ 2013-07-23T16:59:12-04:00 ║ ║ 2 ║ 设备 2 ║ 达拉斯 ║ 2013-07-23T16:59:12-04:00 ║ ║ 3 ║ Device3 ║ 芝加哥 ║ 2013-07-23T16:59:12-04:00 ║ ║ 4 ║ Device4 ║ 达拉斯 ║ 2013-07-24T18:00:00-04:00 ║ ║ 5 ║ Device5 ║ 芝加哥 ║ 2013-07-24T18:00:00-04:00 ║ ╚════╩═════════════╩═══════════╩══════════════════ ═════════╝ 地点 ╔═══════════╦═══════════════════════════╗ ║ Site_Name ║ Most_Recent_Updated_Time ║ ╠═══════════╬═══════════════════════════╣ ║ 达拉斯 ║ 2013-07-24T18:00:00-04:00 ║ ║ 芝加哥 ║ 2013-07-24T18:00:00-04:00 ║ ║ 波士顿 ║ 2013-07-24T18:00:00-04:00 ║ ╚═══════════╩═══════════════════════════╝
因此,如果我在脚本运行后运行查询,我希望它返回 Device4 和 Device5。