求助使用gin配合mysql实现一种查询场景

场景:前端POST传入一个字段或者多个字段,gin拿到后如何处理区分传入的是什么?然后去数据库查询,如果查找了就返回这个用户的所有数据,(能被查询的字段只有:name,order_id,phone)期望的结果如:

// 情况1
POST>张三
Rturn—>name:张三,gender:男,age:32,order_id:123456,phone:13888888888
// 场景2
POST>13888888888
Return—>name:张三,gender:男,age:32,order_id:123456,phone:13888888888
// 场景3
POST>13888888888654321
Return—>
name:张三,gender:男,age:32,order_id:123456,phone:13888888888
name:李四,gender:女,age:18,order_id:654321,phone:15555555555

数据库

有三张表user,order,info

user 主表

id name gender age
1 张三 32
2 李四 18

order 分表关联 user.id

id user_id order_id
1 1 123456
2 2 654321

info 分表关联 user.id

id user_id phone
1 1 13888888888
2 2 15555555555

前端

<div class="search-box">
    <form method="post" action="/">
        <input type="text" class="search-txt" name="column" placeholder="查询" />
        <button type="submit" class="search-btn fa fa-search" aria-hidden="true"></button>
    </form>
</div>

后端

func main() {
    // 初始化数据库连接
    config.NewDB()

    // 创建 gin 引擎实例
    router := gin.Default()
    router.LoadHTMLFiles("./static/templates/index.html")
    router.Static("/static", "./static/templates/css")
    router.GET("/", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.html", gin.H{})
    })
    router.POST("/", func(c *gin.Context) {
        column := c.PostForm("column")
        fmt.Println(column)
        c.HTML(http.StatusOK, "index.html", gin.H{
            "result": column,
        })
    })
    // 启动服务
    err := router.Run()
    if err != nil {
        return
    }
}
_YangCong
最佳答案

先写正则匹配出来类型,然后执行sql:

select *
from `order`
         left join user on `order`.user_id = user.id
         inner join info on user.id = info.user_id
where `order`.order_id in (order_id集合)
   or user.name in (name集合)
   or info.phone in (phone集合);
11个月前 评论
_YangCong (作者) 11个月前
Scrooge (楼主) 11个月前
讨论数量: 15
select * from table where name in(1885888588,123456) or phone  in(1885888588,123456) or order_idin(1885888588,123456)
11个月前 评论
Scrooge (楼主) 11个月前
ysnow (作者) 11个月前

如果你使用的gorm 参考
gorm.io/zh_CN/docs/advanced_query....

11个月前 评论
Scrooge (楼主) 11个月前

这种都是加个type区分类型

11个月前 评论
Scrooge (楼主) 11个月前
deatil (作者) 11个月前
Scrooge (楼主) 11个月前
_YangCong

先写正则匹配出来类型,然后执行sql:

select *
from `order`
         left join user on `order`.user_id = user.id
         inner join info on user.id = info.user_id
where `order`.order_id in (order_id集合)
   or user.name in (name集合)
   or info.phone in (phone集合);
11个月前 评论
_YangCong (作者) 11个月前
Scrooge (楼主) 11个月前

我觉最好的方法还是从提交上来的数据做区分是最好。因为查询的字段识别度还是很高的,国内手机号11位数字,订单号纯数字,名字中文、英文、数字的组合。如果你通过SQL去解决,很容易出现慢查询

column := c.PostForm("column")

if isPhone(column) {
   // 通过手机号查询符合的结果
} else if isOrderId(column) {
  // 通过订单号查询符合的结果
} else {
  // 通过名字查询符合的结果
}

// 如果是多个查询条件,字符串切割下column,for循环查询合并下结果集就可以了
11个月前 评论
船长☀ (作者) 11个月前
Scrooge (楼主) 11个月前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!