// SELECT `id`,`title` FROM `article` ORDER BY `created_at` ASC
g.Model("article").Fields("id,title").OrderAsc("created_at").All()
// SELECT `id`,`title` FROM `article` ORDER BY `views` DESC
g.Model("article").Fields("id,title").OrderDesc("views").All()
// SELECT `id`,`title` FROM `article` ORDER BY RAND()
g.Model("article").Fields("id,title").OrderRandom().All()
8 Comments
扶程星云
关于
group
,我今天折腾了一上午,将结果写下来供大家参考。其中,第一个
Fields
是要count
的字段,第二个Fields
是最外层的select
字段列表。 解析出来的sql
语句是:郭强
建议:
harley
榕树
想指定状态值来排序,但是m.Order()会被加上``的符号,有其他办法吗?
小陈
功能好多啊, 完全记不住啊.....
kim
使用sqlserver数据库,
model.OrderDesc("start_time").Page(req.PageNo, req.PageSize).ScanAndCount(&res.CarDistanceAlarms, &res.RecordCount, true)
OrderDesc()方法和Page()方法链式写的话,生成的sql语句有问题,会报错但是err返回为nil,单独调用这两个方法就没问题。
在先排序后分页的情况下,无法这样链式调用。
kim
如果不加where条件就没问题,加了where条件,有可能会报错
kim
查询代码:
测试用例一:
结果:
=== RUN TestDBPaging
2024-03-01 17:52:40.026 [DEBU] {5899dae33e9bb8177845653edb98b9bc} [ 0 ms] [default] [third_party_info] [rows:1 ] [txid:1] SELECT COUNT(1) FROM car_distance_alarm
2024-03-01 17:52:40.033 [DEBU] {5899dae33e9bb8177845653edb98b9bc} [ 2 ms] [default] [third_party_info] [rows:2 ] [txid:1] SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY start_time DESC ) as ROWNUMBER_, id,car_name,card_no,dept,position,distance,start_time,end_time,duration,car_emp_id FROM car_distance_alarm ) as TMP_ WHERE TMP_.ROWNUMBER_ > 0 AND TMP_.ROWNUMBER_ <= 10
2024-03-01 17:52:40.033 [DEBU] {5899dae33e9bb8177845653edb98b9bc} [ 0 ms] [default] [third_party_info] [rows:0 ] [txid:1] COMMIT
可以正常分页查询。
测试用例二:
结果:
=== RUN TestDBPaging
2024-03-01 17:57:30.141 [DEBU] {dcbe2612849bb817290aba5ebad52e94} [ 4 ms] [default] [third_party_info] [rows:0 ] [txid:1] BEGIN
2024-03-01 17:57:30.225 [DEBU] {dcbe2612849bb817290aba5ebad52e94} [ 2 ms] [default] [third_party_info] [rows:1 ] [txid:1] SELECT COUNT(1) FROM car_distance_alarm WHERE (dept = '车队') AND (car_name like '%1号材料车%') AND (c ard_no like '%11%') AND (start_time >= '2024-02-29 12:00:00') AND (start_time <= '2024-02-29 18:00:00')
2024-03-01 17:57:30.225 [DEBU] {dcbe2612849bb817290aba5ebad52e94} [ 0 ms] [default] [third_party_info] [rows:0 ] [txid:1] COMMIT
{
RecordCount: 0,
CarDistanceAlarms: [],
}
<nil>
--- PASS: TestDBPaging (0.10s)
PASS
生成的count()sql里面有一个条件字段存在很大的空格,然后查询不出来数据,但是实际上,数据库是可以查询出数据的,把空格去掉复制生成的sql去数据库执行是可以查询到数据的。
生成的sql是这样的:
将空格去掉后在数据库执行是可以查到数据的: