「GoCN酷Go推荐」postgresql ORM 框架 go-pg系列(三)

之前的两篇都是入门篇,今天我们深入了解下go-pg的select,insert,delete,update的多种玩法。

【GoCN酷Go推荐】postgresql ORM 框架 go-pg系列(一)

【GoCN酷Go推荐】postgresql ORM 框架 go-pg系列(二)

零、设计理念

我们的目标是帮助您编写SQL,而不是用自定义方言隐藏或替换它。Go-pg查询生成器有以下帮助:

•将长查询分割为逻辑上分离的块;•用正确的转义值来替换?占位符•通过go models生成列的列表和一些join连接

举例有如下go代码:

err := db.Model(book).
    ColumnExpr("lower(name)").
    Where("? = ?", pg.Ident("id"), "some-id").
    Select()

生成如下的sql语句

SELECT lower(name)
FROM "books"
WHERE "id" = 'some-id'

一、Select查询

1、1 sql和go-pg对照表

SQL go-pg
SELECT col1, col2 Column("col1", "col2")
SELECT col1, col2 ColumnExpr("col1, col2")
SELECT count() ColumnExpr("count()")
SELECT count("id") ColumnExpr("count(?)", pg.Ident("id"))
FROM "table1", "table2" Table("table1", "table2")
FROM table1, table2 TableExpr("table1, table2")
JOIN table1 ON col1 = 'value1' Join("JOIN table1 ON col1 = ?", "value1")
JOIN table1 ON col1 = 'value1' Join("JOIN table1").JoinOn("col1 = ?", "value1")
LEFT JOIN table1 ON col1 = 'value1' Join("LEFT JOIN table1 ON col1 = ?", "value1")
WHERE id = 1 Where("id = ?", 1)
WHERE "foo" = 'bar' Where("? = ?", pg.Ident("foo"), "bar")
WHERE id = 1 OR foo = 'bar' Where("id = ?", 1).WhereOr("foo = ?", "bar")
GROUP BY "col1", "col2" Group("col1", "col2")
GROUP BY col1, col2 GroupExpr("col1, col2")
GROUP BY "col1", "col2" GroupExpr("?, ?", pg.Ident("col1"), pg.Ident("col2"))
ORDER BY "col1" ASC Order("col1 ASC")
ORDER BY col1 ASC OrderExpr("col1 ASC")
ORDER BY "col1" ASC OrderExpr("? ASC", pg.Ident("col1"))
LIMIT 10 Limit(10)
OFFSET 1000 Offset(1000)

1、2 示例

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值