在GO语言sqlx包中,如何使用 like 模糊查询?
这样拼接 "%?" 后为什么查询没有结果?
sqlx.DB.Select(&users, "SELECT * FROM user WHERE name LIKE %?% OR email LIKE %?%", keyword,keyword)
实际上是错误的,问号是sqlx的占位符百分号是sql的通配符,硬拼接只会抛出一个异常
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(MISSING) OR email LIKE ? ' at line 1
方法一:
一种方法是从变量入手,改变变量值
sqlx.DB.Select(&users,
"SELECT * FROM user WHERE name LIKE ? OR email LIKE ?", "%" + keyword + "%", "%" + keyword + "%")
方法二:
一种方法是使用CONCAT
sqlx.DB.Select(&users, "SELECT * FROM USER WHERE name LIKE CONCAT(?, '%' ) OR email LIKE CONCAT(?, '%')", keyword, keyword)