gpt4 book ai didi

MySQL 错误 1064 : search query not working as expected

转载 作者:IT王子 更新时间:2023-10-29 02:29:11 25 4
gpt4 key购买 nike

我正在尝试编写用于搜索表的查询,但我收到了一般的 1064 MySQL 语法错误。我没有发现我的查询有任何问题......事实上,我有另一个查询就像它一样工作正常。

查询使用 Go 中的 SQL 驱动程序,所有 ? 都将在查询运行之前转换为值。

这是我的错误:

Error 1064: 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 'SELECT tax.* FROM tax JOIN user_tax ON user_tax.tax_id = tax.id WHERE u' at line 3

例如,这是工作查询:

SELECT tax.*
FROM tax
JOIN user_tax
ON user_tax.tax_id = tax.id
WHERE user_tax.user_id = ?
AND tax.deleted_at IS NULL
AND user_tax.deleted_at IS NULL

上面的查询将查找给定用户的所有税务记录。

现在我正在尝试进行完全相同的查询,只是现在它是一个“搜索”查询。它接受一个搜索字符串,并在税表的 namerate 列中查找它。就是这样:

SET @searchString = '%?%';

SELECT tax.*
FROM tax
JOIN user_tax
ON user_tax.tax_id = tax.id
WHERE user_tax.user_id = ?
AND tax.deleted_at IS NULL
AND user_tax.deleted_at IS NULL
AND tax.name LIKE @searchString
OR tax.rate LIKE @searchString

这是代码中的查询:

var taxes []Tax
err := r.db.Select(&taxes, `
SET @query = '%?%';

SELECT tax.*
FROM tax
JOIN user_tax
ON user_tax.tax_id = tax.id
WHERE user_tax.user_id = ?
AND tax.deleted_at IS NULL
AND user_tax.deleted_at IS NULL
AND tax.name LIKE @query
OR tax.rate LIKE @query
`, q, userId)

最佳答案

如果你想避免多次绑定(bind)相同的值,你可以在交叉连接子查询中绑定(bind)一次并重用该值:

SELECT tax.*
FROM tax
JOIN user_tax
ON user_tax.tax_id = tax.id
CROSS JOIN (SELECT ? as q) sub
WHERE user_tax.user_id = ?
AND tax.deleted_at IS NULL
AND user_tax.deleted_at IS NULL
AND (tax.name LIKE sub.q
OR tax.rate LIKE sub.q)

现在只需绑定(bind) %s% 作为第一个参数。

关于MySQL 错误 1064 : search query not working as expected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45388963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com