条件: userId, keyword, starttime, endtime, loglevel(in 查询);
动态拼接sql使用如下: 原始sql拼接;
执行语句为
***err := m.conn.QueryRow( &count, sqlPageList + where, values...)***
mysql in查询的逻辑: 将in查询条件使用正则匹配"#“替换成” ?,? ", 然后占位符拼接参数Array 数组;
执行上面查询语句即可。
func (m *defaultVsmAuditLogModel) SelectCount(userId int64, req types.ReqAuditLog) (int, error) {
var sqlPageList, where string
var values []interface{}
sqlPageList = "select count(1) " +
"from vsm_audit_log where 1=1 "
if userId != 0 {
where = where + " AND req_user = ?"
values = append(values, userId)
}
if req.Keyword != "" {
where = where + " AND operate_record like ?"
values = append(values, "%" + req.Keyword + "%")
}
if req.StartTime != ""{
where = where + " AND timestamp >= ?"
st, _ := time.Parse("2006-01-02", req.StartTime)
values = append(values, st)
}
if req.EndTime != ""{
where = where + " AND timestamp < ?"
et, _ := time.Parse("2006-01-02", req.EndTime)
values = append(values, et)
}
var levelArr []int
var count int
if req.LogLevel!=nil && len(req.LogLevel)>0{
//数组存在
for _, levelStr := range req.LogLevel {
var a int
switch *levelStr{
case "高级":
a = 4
case "中级":
a = 3
case "低级":
a = 2
case "信息级":
a = 1
case "无":
a = 0
}
levelArr = append(levelArr, a)
}
where = where + " AND log_level in (#)"
var dstr []string
for l := 0; l < len(req.LogLevel); l++ {
values = append(values, levelArr[l])
dstr = append(dstr, "?")
}
regReplace:= strings.Join(dstr, ",")
data := sqlPageList + where
rep, _ := regexp.Compile("\\#")
sql := rep.ReplaceAllLiteralString(data, regReplace)
err := m.conn.QueryRow( &count, sql, values...)
switch err {
case nil:
return count, nil
case sqlc.ErrNotFound:
return 0, nil
default:
return 0, err
}
}else{
err := m.conn.QueryRow( &count, sqlPageList + where, values...)
switch err {
case nil:
return count, nil
case sqlc.ErrNotFound:
return 0, nil
default:
return 0, err
}
}
}
参考文档: https://github.com/suyaoli/example-001/blob/master/main.go