gpt4 book ai didi

ruby-on-rails - Rails 3 DISTINCT QUERY

转载 作者:行者123 更新时间:2023-12-03 11:31:52 24 4
gpt4 key购买 nike

有一个用户,UserBadge和徽章表。它们通过has_many连接。一个用户可以有多个相同的徽章,但是我想查询一个唯一的列表。

@user.badges.select("DISTINCT id").order("created_at DESC")

引发错误:
SQLite3::SQLException: near "DISTINCT": syntax error:

正确的语法是什么?

编辑:添加了整个错误
SQLite3::SQLException: near "DISTINCT": syntax error: SELECT "badges".*, DISTINCT badges.id FROM "badges" INNER JOIN "userbadges" ON "badges".id = "userbadges".badges_id WHERE (("userbadges".user_id = 1))

难道是选择和区分之间的逗号?

最佳答案

SELECT之后,DISTINCT需要保持平直,即

SELECT DISTINCT(badges.id), "badges".* FROM "badges" INNER JOIN "userbadges" ON "badges".id = "userbadges".badges_id WHERE (("userbadges".user_id = 1))

尝试:
@user.select("DISTINCT(badges.id), badges.*").badges.order("badges.created_at DESC")

PostgreSQL要求您具有用于不重复字段的订单声明:
@user.select("DISTINCT(badges.id), badges.*").badges.order("badges.id").order("badges.created_at DESC")

关于ruby-on-rails - Rails 3 DISTINCT QUERY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5901828/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com