改进代码res := common.DB.Raw("SELECT * FROM(SELECT * FROM flaws WHERE facility_id = ? AND label LIKE ? "+ "UNION SELECT * FROM issues WHERE facility_id = ? AND label LIKE ? "+ "UNION SELECT * FROM records WHERE facility_id = ? AND label LIKE ? "+ "UNION SELECT * FROM qualities WHERE facility_id = ? AND label LIKE ? "+ "UNION SELECT * FROM inspections WHERE facility_id = ? AND label LIKE ?)"+ "AS combined_tables LIMIT ? OFFSET ?", code, "%"+strconv.Itoa(label)+"%", code, strconv.Itoa(label)+"%", code, strconv.Itoa(label)+"%", code, strconv.Itoa(label)+"%", code, strconv.Itoa(label)+"%", pageSize, offset).Find(&req)
时间: 2024-01-20 15:03:59 浏览: 120
xebia-android-flaws:XKE - Android 应用安全漏洞示例
在这段代码中,可以使用参数化查询来防止 SQL 注入攻击。另外,可以考虑将查询语句拆分成多个简单查询,然后使用 Go 语言的 goroutine 将它们并行执行,以提高查询效率。以下是修改后的代码:
```
res1 := common.DB.Raw("SELECT * FROM flaws WHERE facility_id = ? AND label LIKE ?", code, "%"+strconv.Itoa(label)+"%")
res2 := common.DB.Raw("SELECT * FROM issues WHERE facility_id = ? AND label LIKE ?", code, strconv.Itoa(label)+"%")
res3 := common.DB.Raw("SELECT * FROM records WHERE facility_id = ? AND label LIKE ?", code, strconv.Itoa(label)+"%")
res4 := common.DB.Raw("SELECT * FROM qualities WHERE facility_id = ? AND label LIKE ?", code, strconv.Itoa(label)+"%")
res5 := common.DB.Raw("SELECT * FROM inspections WHERE facility_id = ? AND label LIKE ?", code, strconv.Itoa(label)+"%")
var wg sync.WaitGroup
wg.Add(5)
go func() {
defer wg.Done()
res1.Find(&req)
}()
go func() {
defer wg.Done()
res2.Find(&req)
}()
go func() {
defer wg.Done()
res3.Find(&req)
}()
go func() {
defer wg.Done()
res4.Find(&req)
}()
go func() {
defer wg.Done()
res5.Find(&req)
}()
wg.Wait()
// Pagination
total := len(req)
if pageSize > 0 && offset >= 0 {
res = req[offset:min(offset+pageSize, total)]
} else {
res = req
}
```
注意,这里只是将查询语句拆分成多个简单查询,并行执行。如果需要进一步提高查询效率,可以考虑使用缓存来避免重复查询。
阅读全文