如何在 Go 的 sqlx 查询中使用通配符?
How to use wildcard in sqlx query in Go?
我将 sqlx 与 mysql 数据库一起使用,想查询 author
table 以查找以特定字母开头的名称。这是查询:
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
查询的示例,但找不到任何示例。所以想知道我该如何解决这个问题?
你那里有 %
,那不是 ?
、?
或 :p1
、:p2
、</code>, <code>
(无论 MySQL 参数占位符是什么)
我会这样做:
sqlx.DB.Select(&authors, "SELECT * FROM author WHERE first_name LIKE ? OR last_name LIKE ?",
letter+"%",letter+"%")
通配符 %
应该是参数字符串的一部分。
您可以使用 SQL 字符串连接:
SELECT * FROM author
WHERE first_name LIKE ? || '%' OR last_name LIKE ? || '%'
另一种方法是使用 CONCAT:
sqlx.DB.Select(&authors, "SELECT * FROM author WHERE first_name LIKE CONCAT(?, '%') OR last_name LIKE CONCAT(?, '%')", letter, letter)
希望对您有所帮助!
我将 sqlx 与 mysql 数据库一起使用,想查询 author
table 以查找以特定字母开头的名称。这是查询:
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
查询的示例,但找不到任何示例。所以想知道我该如何解决这个问题?
你那里有 %
,那不是 ?
、?
或 :p1
、:p2
、</code>, <code>
(无论 MySQL 参数占位符是什么)
我会这样做:
sqlx.DB.Select(&authors, "SELECT * FROM author WHERE first_name LIKE ? OR last_name LIKE ?",
letter+"%",letter+"%")
通配符 %
应该是参数字符串的一部分。
您可以使用 SQL 字符串连接:
SELECT * FROM author
WHERE first_name LIKE ? || '%' OR last_name LIKE ? || '%'
另一种方法是使用 CONCAT:
sqlx.DB.Select(&authors, "SELECT * FROM author WHERE first_name LIKE CONCAT(?, '%') OR last_name LIKE CONCAT(?, '%')", letter, letter)
希望对您有所帮助!