SQL嵌套查询
我有一个图像表和一个位置表 我想检索图像列表,这些图像是特定边界内每个位置的最新图像。
SELECT * FROM images
WHERE location_id IN
(SELECT id FROM locations
WHERE latitude > 17.954 AND latitude < 52.574
AND longitude > -107.392 AND longitude < -64.853)
这是使用嵌套查询,但我们可以通过连接实现相同的目的。 如果我们想要每个位置的所有图像,则此方法有效,但我只想获取每个位置 1 个图像(最新的)
以下是这些表的主要字段,
table "images"
integer "id"
text "image_name"
text "caption"
integer "location_id"
datetime "created_at"
datetime "updated_at"
integer "view_count"
table "locations"
integer "id"
text "name"
float "longitude"
float "latitude"
datetime "created_at"
datetime "updated_at"
string "city"
string "address"
string "province"
string "country"
string "post_code"
您知道吗?
如果有办法使用 Rails activerecord API 来做到这一点,那就加分了
I have an images table and a locations table
I want to retrieve a list of images that are the latest images for each location within a certain boundaries.
SELECT * FROM images
WHERE location_id IN
(SELECT id FROM locations
WHERE latitude > 17.954 AND latitude < 52.574
AND longitude > -107.392 AND longitude < -64.853)
This is with a nested query, but we could achieve the same with a join.
This works if we want all images for each location, but I would like to get only 1 image per location (the most recent)
Here are the main fields of these tables
table "images"
integer "id"
text "image_name"
text "caption"
integer "location_id"
datetime "created_at"
datetime "updated_at"
integer "view_count"
table "locations"
integer "id"
text "name"
float "longitude"
float "latitude"
datetime "created_at"
datetime "updated_at"
string "city"
string "address"
string "province"
string "country"
string "post_code"
any idea?
Bonus points if there is a way to do this using rails activerecord API
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将需要在子查询中使用别名和聚合。
You will need to make use of aliases and aggregation in a sub-query.
如果您在同一位置有 2 个具有相同更新日期的日期,则应按日期描述使用前 1 排序
You Should use Top 1 Ordering by your date desc, incase you have 2 dates in the same location with the Same Updated Date