0

我在 Go 上使用 SqlBoiler 向 PostgreSQL 数据库发送请求,但是当尝试通过其中一个字段对数据库进行排序时,它返回 0 行。

首先我运行一个计数(如下详述),如果计数返回多于或等于一行,那么我查询数据库以获取所有结果。

这将返回正确的行数:

res, _ := models.MT(
        Where("(mt_mas = ? or mt_mem like ?) and mt_group = ?", uint(uid), `%"`+strconv.Itoa(uid)+`"%`, bool(mt_group_bool)),
    ).Count(CTX, DB)

尽管查询参数完全相同,但这不会返回任何行:

res, _ := models.MT(
        Where("(mt_mas = ? or mt_mem like ?) and mt_group = ?", uint(uid), `%"`+strconv.Itoa(uid)+`"%`, bool(mt_group_bool)),
        OrderBy(`mt_mas`),
    ).Count(CTX, DB)

这是我在检查行数后获取所有行的方式:

res, err := models.MT(
        Where("(mt_mas = ? or mt_mem like ?) and mt_group = ?", uint(uid), `%"`+strconv.Itoa(uid)+`"%`, bool(mt_group_bool)),
        OrderBy(`mt_mas`),
    ).All(CTX, DB)

从上面的请求中读取错误时,它会打印出来<nil>,一切看起来都很好。

如前所述,数据库是 Postgres(版本 PostgreSQL 13.3),列如下:

  • mt_mas (integer)
    此列保存此行所有者的 uid。
  • mt_mem(字符变化 [1000])
    此列包含用户成员 uid:s 的 JSON 列表。
  • mt_group (boolean)
    此列显示此行是不是一组。

数据库行示例:
| mt_mas | mt_mem | mt_group | | :----: | :----: | :--------: | | 1 | {"1", "2"} | 假 |

4

1 回答 1

0

好的,解决方案比预期的要简单。@Gari Singh(https://stackoverflow.com/users/5529712/gari-singh)实际上在上面的评论中指出了这一点,但我想我会写在这里,所以问题登记为已解决。

解决方案是简单地不在计算结果的查询中排序。所以正确的计数代码应该是:

res, _ := models.MT(
        Where("(mt_mas = ? or mt_mem like ?) and mt_group = ?", uint(uid), `%"`+strconv.Itoa(uid)+`"%`, bool(mt_group_bool)),
    ).Count(CTX, DB)

然后运行查询以获取具有顺序的实际行,如下所示:

res, err := models.MT(
        Where("(mt_mas = ? or mt_mem like ?) and mt_group = ?", uint(uid), `%"`+strconv.Itoa(uid)+`"%`, bool(mt_group_bool)),
        OrderBy("mt_mas"),
    ).All(CTX, DB)

感谢您的帮助!:)

于 2021-08-03T09:05:50.293 回答