为什么 gorm postgresql 在“)”处或附近抛出 pq:语法错误?

SELECT_QUERY = `SELECT * FROM events WHERE c_id = ? AND start_time > ? and

                                    end_time < ?`


query := sr.db.Raw(SELECT_QUERY, request.GetCId(), startTime, endTime)


    var v = request.GetVIds()

    if len(v) > 0 {

        query = query.Where(` v_id IN (?) `, v)

    } //Only this block introduces first ) after end_time


var c = request.GetStatus().String()

    if len(c) > 0 {

        query = query.Where( " status = ? ", c) // this introduces the other opening brace //after AND

    }

以下是在日志中生成并找到的查询


 SELECT * FROM events WHERE c_id = 1 AND start_time > '2020-04-16 18:42:00' and

                                        end_time < '2020-04-16 18:45:50' ) AND ( v_id IN (1,2)) AND ( status = 'STATUS_MIDDLE_CLASS'  ORDER BY  start_time DESC  LIMIT 5 OFFSET 1

stackoverflow 和互联网文章中的其他解决方案没有帮助。


PS:是不是因为我混合了 db.Raw( ) 和 query.Where() ?


白衣非少年
浏览 171回答 2
2回答

慕桂英546537

改变?到 $1 并不能解决问题。基本上有几件事解决了这个问题。1)混合是一个Raw问题query.Where。Raw查询后sr.db.Where2)SELECT_QUERY = `SELECT * FROM events WHERE c_id = ? AND start_time > ? and&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; end_time < ?`已经有了select * from。然后使用query := sr.db.Raw(SELECT_QUERY, request.GetCId(), startTime, endTime)引入嵌套select *.所以,改变 SELECT_QUERY 如下SELECT_QUERY = `events WHERE c_id = ? AND start_time > ? and&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; end_time < ?`解决了这个问题。

泛舟湖上清波郎朗

我找到了一个解决方法,当我尝试在 Go/Gorm 解决方案中添加时间戳时收到的错误,PostgreSQL 等效default: now()于default: time.Now().Format(time.RFC3339)我收到错误是因为我使用 AutoMigrate() 在 PostgreSQL 中创建表。我发现的一个问题是尝试使用函数的默认值而不是字符串(可用于固定时间戳)时。所以我不得不进入DataGrid(因为我使用JetBrains,但您可以使用任何 PostgreSQL 管理工具,如pgAdmin)并手动添加默认为的时间戳字段,now()或者仅更新现有字段以添加默认的now().&nbsp;然后在 Go 中进行下一次构建时,错误就会消失。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go