繁体   English   中英

如何将多个SQL查询合并为单个查询?

[英]How to combine multiple sql queries into single query?

我正在使用postgressql开发Spring Boot框架。 以下是示例查询1,2,... n。 这些查询工作正常。 但是我必须将这些查询合并到单个查询中,因为表中包含大量数据,因此由于性能问题,我无法多次(在for循环中)运行查询。 但是我不知道将这些查询组合在一起。

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;

任何想法都可以完成任务。 我是春季和冬眠世界的初学者级开发人员。 请提出解决方案或任何有用的链接。

提前致谢

您可以使用条件聚合。

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;

这是一种方法:

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;
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,其性能类似于低数量的过滤器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM