How to use wildcard in sqlx query in Go?

huangapple go评论90阅读模式
英文:

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 ? || '%'

huangapple
  • 本文由 发表于 2016年10月14日 17:03:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/40039154.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定