我有两张桌子:sales
和products
[Products]
+-------+-------------------+
| id | name |
+-------+-------------------+
| 1 | product number 1 |
| 2 | product number 2 |
| 3 | product number 3 |
+-------+-------------------+
[Sales]
+-------+------------+------+
| id | product_id | qty |
+-------+------------+------+
| 1 | 2 | 100 |
| 2 | 2 | 35 |
| 3 | 1 | 1 |
+-------+-------------------+
我想用JavaEE和JPA显示类似的内容:
Most selled products :
+------------------+------------+
| Product name | Quantity |
+------------------+------------+
| product number 2 | 135 |
| product number 1 | 1 |
+------------------+------------+
我面临两个问题:
这是我尝试过的:
public List<Product> getMostSelledProducts() {
Query q = em.createQuery("SELECT p FROM Sale s RIGHT JOIN Product p GROUP BY s.productId ORDER BY COUNT(s.productId)");
return q.getResultList();
}
我该怎么办?
答案 0 :(得分:1)
不确定这是否有效,没有测试,但如果不起作用,可能会让你走上正确的道路。
SELECT p.name, SUM(s.qty) as Quantity FROM Sales s
INNER JOIN Product p ON s.product_id = p.id
GROUP BY s.product_id
ORDER BY Quantity DESC