【问题标题】:How to combine multiple sql queries into single query?如何将多个sql查询组合成一个查询?
【发布时间】:2017-09-02 17:41:29
【问题描述】:

我正在使用 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;

完成任务的任何想法。我是 spring 和 hibernate 世界的初级开发人员。 请提出解决方案或任何有用的链接。

提前致谢

【问题讨论】:

  • 没有联合不适用于该场景
  • 哦,那么对不起。我想您可以使用答案中提供的其他方法。祝你好运。

标签: sql postgresql hibernate spring-boot


【解决方案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;

【讨论】:

  • 在我的例子中,有 n 个产品和 n 个价格范围,我需要在休眠查询中传递这些输入。
【解决方案2】:

这是一种方法:

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;

【讨论】:

  • 感谢回复。在我的例子中,我在 hibernate(HBL) 中编写查询,所以我需要在列表中传递产品和价格。请分享您对此的看法。
  • @user320676 。 . .我不使用 Hibernate,但您应该能够传入诸如此类的基本逻辑表达式。
【解决方案3】:
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 语句,性能类似于低数量的过滤器。

【讨论】:

    猜你喜欢
    • 2018-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多