You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确查询同时拥有指定联合产品且总价低于100的公司?

问题分析与解决方案

原查询返回0行的核心原因是子查询的分组字段错误:你在子查询里按products.id分组,而每个products.id对应单条产品记录,每条记录仅能对应一个union_product_id,因此COUNT(distinct union_product_id)永远只能是1,不可能等于2,自然查不到符合条件的结果。

要实现需求,子查询需要按company_id分组,这样才能从公司维度统计是否同时拥有union_product_id=1和union_product_id=2的产品,以及这些产品的总价之和。

修正后的查询语句

select * from "companies" where exists
(
    select company_id from "products"
             where "companies"."id" = "products"."company_id"
               and "union_product_id" in (1, 2)
             group by company_id
             having COUNT(distinct union_product_id) = 2 AND SUM(price_per_one_product) < 100
)

关键修正点

  • 将子查询的group by id改为group by company_id:切换到公司维度聚合数据,才能统计该公司覆盖的union产品类型数量
  • 子查询选择company_id即可,无需选择products.id,因为我们仅需验证公司是否满足条件

内容的提问来源于stack exchange,提问作者Alexxosipov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 22:46:04