改进代码var req []*Total res := db.Scopes(models.Paginate(page, pageSize)).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).Find(&req)
时间: 2024-01-29 09:04:42 浏览: 71
可以尝试使用预编译语句来优化 SQL 查询性能,同时使用占位符来避免 SQL 注入攻击。改进后的代码如下所示:
```go
stmt, err := db.DB().Prepare("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 = ? " +
"LIMIT ? OFFSET ?")
if err != nil {
// 处理错误
}
defer stmt.Close()
req := make([]*Total, 0)
offset := (page - 1) * pageSize
limit := pageSize
rows, err := stmt.Query(code, code, code, code, code, limit, offset)
if err != nil {
// 处理错误
}
defer rows.Close()
for rows.Next() {
var item Total
err := rows.Scan(&item)
if err != nil {
// 处理错误
}
req = append(req, &item)
}
if err := rows.Err(); err != nil {
// 处理错误
}
res := db.Model(&Total{}).Where("facility_id = ?", code).Count(&Total{})
// 处理结果
```
这里我们使用了 `db.DB().Prepare()` 方法来预编译 SQL 查询语句,并使用占位符 `?` 来代替变量,从而避免了 SQL 注入攻击。
同时,我们也将分页查询的 `LIMIT` 和 `OFFSET` 参数移到了 SQL 查询语句中,以避免使用 `Scopes()` 方法产生额外的查询开销。在查询结果时,我们使用 `stmt.Query()` 方法来执行查询,并使用 `rows.Scan()` 方法将查询结果映射到结构体中。
最后,我们使用 `db.Model().Where().Count()` 方法来查询总记录数,并将结果返回给调用者。
阅读全文
相关推荐


















