我正在尝试执行以下查询MySQL
通过此查询,可以获取比赛中汽车的分类,以及这些汽车的驾驶员
查询:
SELECT * FROM results
INNER JOIN cars ON results.idCar = cars.Id
INNER JOIN drivers ON cars.id = drivers.idCar
WHERE idSesson = 7
ORDER BY classification
ASC
此查询返回 2 个模型:结果、会话。并返回每辆车的驾驶员列表
问题是它返回每个飞行员的结果,也就是说,相同的结果可以出现3次,只是飞行员不同,我想在一个JSONArray
使用此查询,我使用此实现
result := structs.Result{}
lastResult := structs.Result{}
results := []structs.Result{}
driver := structs.Driver{}
drivers := []structs.Driver{}
for rows.Next() {
var sesson structs.Sesson
var car structs.Car
err = rows.Scan(&result.Id, &sesson.Id, &car.Id, &result.Type, &result.Classification, &result.Category, &car.Id, &car.IdTeam,
&car.Name, &car.Number, &car.Model, &car.Manufacturer, &car.TyerBrand, &car.CarImage, &driver.Id, &driver.IdCar,
&driver.Name, &driver.Age, &driver.DateOfBrith, &driver.Country, &driver.FlagCountry, &driver.Facebook, &driver.Twitter, &driver.Website, &driver.Picture)
if err != nil {
fmt.Printf("Error in scan")
panic(err.Error())
}
result.Sesson = sesson
result.Car = car
drivers = append(drivers, driver) // i stor the drivers in one array
// check if end the duplicated, info
if (lastResult.Id != 0 && lastResult.Id != result.Id) {
results = append(results, lastResult)
}
// store the last result
lastResult = result
}
// add last result
results = append(results, lastResult)
// save the drivers in JSONArray in each jsonObject
for i := 0; i < len(results); i++ {
for j := 0; j < len(drivers); j++ {
if (results[i].Car.Id == drivers[j].IdCarro) {
results[i].Drivers = append(results[i].Drivers, drivers[j])
}
}
}
// transform data in json
jsonData, err := json.Marshal(results)
if err != nil {
fmt.Printf("error in marsahl")
}
db.Close()
return jsonData
这是一个好的实现吗?对于这个问题??
手掌心
相关分类