gpt4 book ai didi

postgresql - ActiveJDBC 使用聚合从多个表中选择记录

转载 作者:行者123 更新时间:2023-11-29 13:20:38 25 4
gpt4 key购买 nike

情况是这样的。我有一个包含多个多对多关系的表。

game (id, name, year_release ...)
game_price (game_id, price_id, amount)
price(id, label -- new game, used game)
category(id, name)
game_category(game_id, category_id)

现在我想为每个游戏选择一个包含 20 款游戏的列表、价格列表和类别列表。

在 SQL 中我会做这样的事情

select game.id, game.name string_agg(price.label||':'game_price.amount), string_agg(category.name)
from game
left join game_price gp on (game.id = gp.game_id)
left join price on (price.id = price_id)
left join game_category gc on (game.id = gc.game_id)
left join category on (category.id = category_id)
group by game.id

我这里有一个例子:http://javalite.io/lazy_and_eager对于一对多,但对于多对多则没有。

我是否必须先加载所有 game_price 然后加载所有 game_category,就像这样?

List<GamesPrices> gamesPrices = GamesPrices.findAll(Game.class, Price.class)
List<GamesCategories> gamesCategories = GamesCategories.findAll(Game.class, Category.class)

但是我怎样才能循环获取每个游戏的所有信息呢?

最佳答案

有两种方法:

与模型:

List<Game> games = Game.where(criteria, param1, param2).include(Price.class, Category,class).limit(20);
for(Game g: games){
List<Price> prices = g.getAll(Price.class);
List<Category> categories = g.getAll(Category.class);
}

没有模型:

String sql = "select game.id, game.name string_agg(price.label||':'game_price.amount), string_agg(category.name)" + 
"from game" +
"left join game_price gp on (game.id = gp.game_id)" +
"left join price on (price.id = price_id)" +
"left join game_category gc on (game.id = gc.game_id)" +
"left join category on (category.id = category_id)" +
"group by game.id";

List<Map> results = Base.findAll(sql);

希望对您有所帮助!

关于postgresql - ActiveJDBC 使用聚合从多个表中选择记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42426865/

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