2017-04-07 137 views
0

我正在使用postgressql的spring引导框架。 下面是示例查询1,2,... n。这些查询工作正常。但是我必须将这些查询合并到单个查询中,因为表的数据量很大,所以由于性能问题,我无法多次运行查询(在for循环中)。但我没有想到将这些查询结合起来。如何将多个sql查询合并为一个查询?

1. SELECT product_name, count(*) FROM Products WHERE product_name='pro_a1' and price between 20 and 30 group by product_name; 

2. SELECT product_name, count(*) FROM Products WHERE product_name='pro_b1' and price between 50 and 70 group by product_name; 

我想把上面的查询合并成一个像下面这样的东西,我无法实现。

SELECT product_name, count(*) FROM Products WHERE product_name in("pro_a1", "pro_b1", ...) and price between (20,30) AND (50,70) AND so on. group by product_name; 

任何想法做任务。我是春季和冬眠世界的初级开发人员。 请建议解决方案或任何有用的链接。

在此先感谢

+0

没有工会不适合场景 – user320676

+0

哦,对不起。我想你可以使用答案中提供的其他方法。祝你好运。 –

回答

1

您可以使用条件聚合。

SELECT product_name 
,count(case when product_name='pro_a1' and price between 20 and 30 then 1 end) 
,count(case when product_name='pro_b1' and price between 50 and 70 then 1 end) 
FROM Products 
group by product_name; 
+0

在我的情况下有n个产品和n个价格范围,我需要在hibernate查询中传递这些输入。 – user320676

0

这是一个方法:

SELECT product_name, count(*) 
FROM Products 
WHERE (product_name = 'pro_a1' and price between 20 and 30) OR 
     (product_name = 'pro_b1' and price between 50 and 70)  
GROUP BY product_name; 

如果你那么想为每个产品单独计数:

SELECT product_name, count(*), 
     SUM((product_name = 'pro_a1' and price between 20 and 30)::int) as cnt_a1, 
     SUM((product_name = 'pro_b1' and price between 50 and 70)::int) as cnt_b1 
FROM Products 
WHERE (product_name = 'pro_a1' and price between 20 and 30) OR 
     (product_name = 'pro_b1' and price between 50 and 70)  
GROUP BY product_name; 
+0

感谢回复。在我的情况下,我在休眠(HBL)中写入查询,所以我需要将产品和价格传递到列表中。请分享你的想法。 – user320676

+0

@ user320676。 。 。我不使用Hibernate,但是你应该能够传入像这样的基本逻辑表达式。 –

0
SELECT product_name, count(*) 
FROM Products 
WHERE product_name='pro_a1' OR product_name='pro_b1' 
AND price between 20 and 30 OR price between 50 and 70 group by product_name; 

我觉得这是更好的方法,简单明了。您可以使用IN语句TOO,其性能类似于过滤器数量较少。