英文:
How to use wildcard in sqlx query in Go?
问题
我正在使用与MySQL数据库一起使用的sqlx,并且想要查询以特定字母开头的author
表中的姓名。以下是查询语句:
sqlx.DB.Select(&authors, "SELECT * FROM author WHERE first_name LIKE ? OR last_name LIKE ?", letter+"%", letter+"%")
但是我得到了以下错误信息:
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 '% OR last_name LIKE ?%'
我查看了文档,但没有找到LIKE
查询的示例。所以想知道如何修复这个问题?
英文:
I'm using sqlx with mysql database and want to query author
table for names which start with certain letters. Here is the query:
sqlx.DB.Select(&authors, "SELECT * FROM author WHERE first_name LIKE ?% OR last_name LIKE ?%", letter,letter)
but I get
> 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 '% OR last_name LIKE ?%'
I've looked in the docs for examples of LIKE
queries but could not find any. So wondering how can I fix this?
答案1
得分: 10
你的代码中有%
,这些应该是?
、?
或者:p1
、:p2
、$1
、$2
(根据MySQL参数占位符的具体情况)。
我会这样写:
sqlx.DB.Select(&authors, "SELECT * FROM author WHERE first_name LIKE ? OR last_name LIKE ?",
letter+"%", letter+"%")
通配符%
应该作为参数字符串的一部分。
英文:
You have %
in there, wouldn't those be ?
, ?
or :p1
, :p2
, $1
, $2
(whatever the MySQL parameter placeholder is)
I would do like this:
sqlx.DB.Select(&authors, "SELECT * FROM author WHERE first_name LIKE ? OR last_name LIKE ?",
letter+"%",letter+"%")
The wildcard %
should be part of the parameter string.
答案2
得分: 4
另一种方法是使用CONCAT函数:
sqlx.DB.Select(&authors, "SELECT * FROM author WHERE first_name LIKE CONCAT(?, '%') OR last_name LIKE CONCAT(?, '%')", letter, letter)
希望对你有帮助!
英文:
Another way to do it is using CONCAT:
sqlx.DB.Select(&authors, "SELECT * FROM author WHERE first_name LIKE CONCAT(?, '%') OR last_name LIKE CONCAT(?, '%')", letter, letter)
Hope it helps!
答案3
得分: 1
你可以使用 SQL 字符串拼接:
SELECT * FROM author
WHERE first_name LIKE ? || '%' OR last_name LIKE ? || '%'
英文:
You can use SQL string concatenation:
SELECT * FROM author
WHERE first_name LIKE ? || '%' OR last_name LIKE ? || '%'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论