【问题标题】:How can i get just one row where some column values are same in knexjs如何在 knexjs 中仅获得一些列值相同的行
【发布时间】:2021-04-12 00:39:58
【问题描述】:

我试图从我的表中获取不同的值

    let records = db
    .select("*")
    .from("user_technical_skill")
    .distinct('technical_skill_id')

例如在user_technical_skill 表中


[{
"id": "84ed9c04-b1d3-4e69-b2d2-c569ad94545f",
"user_id": "5dfbf2cc-38f9-4388-a077-11480e62d893",
"technical_skill_id": "111",
"created_at": "2021-04-11T15:31:39.552Z",
"updated_at": "2021-04-11T15:31:39.552Z"
},
{
"id": "4b0fcdd6-cbab-4fdf-ada6-0154c7956630",
"user_id": "a3b91e2a-5d7e-4528-b496-3a0807299db7",
"technical_skill_id": "111",
"created_at": "2021-04-11T15:48:49.145Z",
"updated_at": "2021-04-11T15:48:49.145Z"
}]

technical_skill_id 为 11 的两列

但它不起作用。我再次得到查询中的两列 我该如何解决这个问题?

【问题讨论】:

  • 你使用的是哪个数据库?
  • 我正在使用的 PostgreSql
  • 您需要所有列还是只需要结果中的 user_technical_skill?

标签: node.js knex.js


【解决方案1】:

如果您需要所有列,您可以使用 group by 而不是 distinct()。

let records = db
    .select("*")
    .from("user_technical_skill")
    .groupBy('technical_skill_id')

否则,如果您在结果中只需要 user_technical_skill 就可以使用

let records = db.from("user_technical_skill").distinct('technical_skill_id')

您不需要 select("*"),因为 distinct 就像一个选择选项。

参考:

【讨论】:

  • @感谢您的回复。但是当我这样做时我得到"name": "error", "length": 248, "severity": "ERROR", "code": "42803", "position": "8", "file": "d:\\pginstaller_12.auto\\postgres.windows-x64\\src\\backend\\parser\\parse_agg.c", "line": "1409", "routine": "check_ungrouped_columns_walker" 错误......
猜你喜欢
  • 2018-11-30
  • 2019-09-17
  • 2019-02-27
  • 2022-11-03
  • 2022-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-16
相关资源
最近更新 更多