改进代码 var req Total rows, err := common.DB.Raw("SELECT * FROM flaws WHERE facility_id = ? "+ "UNION SELECT * FROM issues WHERE facility_id = ? "+ "UNION SELECT * FROM records WHERE facility_id = ? "+ "UNION SELECT * FROM qualities WHERE facility_id = ? "+ "UNION SELECT * FROM inspections WHERE facility_id = ?", code, code, code, code, code).Rows() if err != nil { resp.Code = 400 resp.Msg = "记录不存在" ctx.JSON(400, resp) return } for rows.Next() { common.DB.ScanRows(rows, &req) } resp.Data = req ctx.JSON(200, resp)
时间: 2024-01-11 09:03:14 浏览: 127
REM-REQ.rar_DSP2407_REM_site:www.pudn.com
可以改进的地方如下:
1. 可以将查询语句中的 UNION 操作改为 INNER JOIN 操作,这样可以减少查询的时间复杂度。同时,使用 INNER JOIN 还可以避免查询结果中出现重复的记录。
2. 在执行查询语句之前,可以先检查传入的 code 参数是否为空或者是否符合要求,以避免 SQL 注入等安全问题。
3. 可以使用 GORM 等 ORM 工具来简化代码,同时还可以避免一些常见的错误,例如忘记关闭数据库连接等。
改进后的代码如下:
```go
if code == "" {
resp.Code = 400
resp.Msg = "参数错误"
ctx.JSON(400, resp)
return
}
var req Total
if err := common.DB.
Table("flaws").
Joins("INNER JOIN issues ON flaws.facility_id = issues.facility_id").
Joins("INNER JOIN records ON issues.facility_id = records.facility_id").
Joins("INNER JOIN qualities ON records.facility_id = qualities.facility_id").
Joins("INNER JOIN inspections ON qualities.facility_id = inspections.facility_id").
Where("flaws.facility_id = ?", code).
Scan(&req).Error; err != nil {
if gorm.IsRecordNotFoundError(err) {
resp.Code = 400
resp.Msg = "记录不存在"
ctx.JSON(400, resp)
return
} else {
resp.Code = 500
resp.Msg = "服务器错误"
ctx.JSON(500, resp)
return
}
}
resp.Data = req
ctx.JSON(200, resp)
```
需要注意的是,上述代码只是简单地演示了一种改进的方法,具体的实现方式可能因为框架、数据库等因素而有所不同。
阅读全文