gpt4 book ai didi

sql - 如何通过 Spring Data JPA 使用 Sum SQL 分组?

转载 作者:行者123 更新时间:2023-12-02 04:27:15 25 4
gpt4 key购买 nike

我想按数量加载畅销产品。这些是我的表格:

Product
id name
1 AA
2 BB

Productorder
order_id product_id quantity
1 1 10
2 1 100
3 2 15
4 1 15

这是我的 Spring 数据存储库:

@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {

@Query(value = "select top 5 p.name, sum(po.quantity) as total_quantity from product p " +
"inner join productorder po " +
"on p.id = po.product_id " +
"group by p.id, p.name " +
"order by total_quantity desc", nativeQuery = true)
List<Product> findTopFiveBestSeller();
}

我收到HsqlException:未找到列:id

我认为这个错误与 id 列没有任何关系,因为两个表都存在该错误。 “group by Sum 查询”是否适用于 Spring 数据?因为这对我来说似乎没什么奇怪的,因为 Spring Data 应该只从数据库中选择产品属性,并且通过这个 sql,我们还选择了 sum(po.quantity)。 Spring数据可以处理这个并将结果转换为列表吗?

PS:我使用嵌入的 HSQLDB 作为数据库。

最佳答案

将 select 语句投影从 p.name 更改为 p.* 后,表明我正在选择多个值,而不仅仅是必须神奇转换的 String 对象到 Product 对象,这有效:

@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {

@Query(value = "select top 5 p.*, sum(po.quantity) as total_quantity from product p " +
"inner join productorder po " +
"on p.id = po.product_id " +
"group by p.id, p.name " +
"order by total_quantity desc", nativeQuery = true)
List<Product> findTopFiveBestSeller();

}

感谢@JMK 和@JB Nizet。

关于sql - 如何通过 Spring Data JPA 使用 Sum SQL 分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27493944/

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