我的rails应用程序中有一个相当复杂的查询, 我加入表A和表B,这样我就可以彻底搜索两个表 然后,我在其ID上对表A进行分组,以删除由表B上的内部联接创建的重复项 然后我要求剩余记录的计数,以便我可以对结果进行分页。
但是当我尝试计算时,这样做会给我以下异常:
ActiveRecord::StatementInvalid (PG::AmbiguousColumn: ERROR: column reference "game_id" is ambiguous
LINE 1: SELECT COUNT(*) AS count_all, game_id AS game_id, region AS ...
^
: SELECT COUNT(*) AS count_all, game_id AS game_id, region AS region FROM "game_data" INNER JOIN "player_participants" ON "player_participants"."game_id" = "game_data"."game_id" WHERE "player_participants"."region" = $1 AND "game_data"."region" = 'NA1' AND "game_data"."status" = 1 GROUP BY "game_data"."game_id", "game_data"."region"):
这是我的导轨代码:
games = GameDatum.joins(:player_participants).where(
player_participants: pp_data,
game_data: g_data
).group(:game_id).order(created_at: :desc).page(page).per(records)
games_json = {}
games_json[:pages] = games.total_pages
games.total_pages使用.count,这就是给我带来问题的。
感谢您的帮助!
答案 0 :(得分:3)
ERROR: column reference "game_id" is ambiguous
您的两个表中看起来都有game_id
列。因此,在查询中使用table_name.column_name
约定。如果您想使用.group('player_participants.game_id')
表格中的group(:game_id)
,请使用game_id
代替player_participants
:
games = GameDatum
.joins(:player_participants)
.where(player_participants: pp_data, game_data: g_data)
.group('player_participants.game_id')
.order(created_at: :desc)
.page(page)
.per(records)
答案 1 :(得分:0)
从纯SQL答案来看,问题是game_id出现在两个表中,因此您需要在查询中具体使用,例如:
SELECT COUNT(*) AS count_all, "player_participants".game_id AS game_id, region AS region FROM "game_data" INNER JOIN "player_participants" ON "player_participants"."game_id" = "game_data"."game_id" WHERE "player_participants"."region" = $1 AND "game_data"."region" = 'NA1' AND "game_data"."status" = 1 GROUP BY "game_data"."game_id", "game_data"."region"
因此,我建议您尝试将table.column_name添加到您的论坛,例如:
。集团(' player_participants.game_id&#39)
很抱歉,我无法提供更多帮助。