我想弄清楚如何构建查询。
我有一个名为Car的课程。
每辆车都归某家公司所有。所以:
Car A.business =" b1",createdAt =" 5月2日......" Car B.business =" b1",createdAt =" 5月3日......" Car C.business =" c1",createdAt =" 4月5日......" Car D.business =" d1",createdAt =" June 1st ..."
等。
因此,企业可以拥有许多汽车。
我想获取数据库中找到的所有汽车,但是,每个企业只需要最新的汽车。
结果将是:
Car B,C,D
除此之外,每辆车都有一个"可用性日期范围",用startDate和endDate定义。
例如:
Car A.business =" b1",createdAt =" May 2nd ..."," startDate = Jun 1st"," endDate = 6月7日"
Car B.business =" b1",createdAt =" 5月3日......"," startDate = 5月20日"," endDate = 6月3日"
Car C.business =" c1",createdAt =" 4月5日......"," startDate = 5月10日"," endDate = 6月30日"
Car D.business =" c1",createdAt =" 4月7日..."," startDate = 5月10日"," endDate = 6月30日"
Car E.business =" d1",createdAt =" June 1st ..."," startDate = May 12th"," endDate = 6月13日"
我不是查询方面的专家,因此,这可能非常简单,只是不确定如何完成它。我需要使用子查询吗?如果除了说最新的(基于createdAt)我还想说:只显示那些从startDate到endDate的内容。
所以:告诉我现在所有可用的汽车,但每个企业只有最新的汽车。 结果将是(如果我现在定义为Jun 4):
C,d,E
有什么想法吗?
答案 0 :(得分:0)
我不知道这是否是最好的方法,但这是最容易确定的方法
SELECT max(car_date), car_name FROM cars GROUP BY car_name
我测试了它,它对我来说很好用
答案 1 :(得分:0)
我不认为通过解析查询可以进行分组。我想实现这一目标的唯一方法是找到所有可用的汽车并手动过滤:
var query = PFQuery(className:"Car")
query.whereKey("startDate", lessThan: now)
query.whereKey("endDate", greaterThan: now)
query.orderByDescending("business")
query.addDescendingOrder("createdAt")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
// manually filter objects (due to the order you always need the
// first car when the business changes)
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
}
根据条目的数量,这可能是可行的。