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

PostgreSQL查询中length_of_stay列值全为第一行值的问题

问题分析:PostgreSQL查询中length_of_stay列值全部重复

原查询代码

select price_total, check_in_date, check_out_date,
price_total / length_of_stay as price_per_day, length_of_stay
from
(select check_out_date - check_in_date as length_of_stay
from bookings b)as table1, bookings b2;

查询输出

price_totalcheck_in_datecheck_out_dateprice_per_daylength_of_stay
1428.302018-08-302018-09-03357.07500000000000004
269.372020-02-112020-02-1467.34250000000000004
111.932020-12-282020-12-2927.98250000000000004
1131.132020-02-262020-02-29282.78250000000000004
391.802020-06-112020-06-1297.95000000000000004
336.002020-06-112020-06-1284.00000000000000004
293.822020-02-162020-02-1873.45500000000000004
2236.922018-09-242018-09-27559.23000000000000004

原因分析

你的查询存在两个核心问题:

  • 无关联的笛卡尔积:用逗号连接子查询table1和主表b2但未指定连接条件,触发了笛卡尔积逻辑——table1的每一行都会和b2的每一行强制匹配。
  • 子查询未关联主表:子查询table1独立计算了整个bookings表的所有停留时长,但没有通过主键(比如booking_id)和b2做关联匹配,导致PostgreSQL默认将table1的第一行值重复映射到b2的所有行上,最终所有结果的length_of_stay都显示为第一行的4。

修正后的查询方案

方案1:直接计算(最简单高效)

不需要子查询,直接在主查询中计算每条记录的停留时长:

select 
  price_total, 
  check_in_date, 
  check_out_date,
  price_total / (check_out_date - check_in_date) as price_per_day, 
  check_out_date - check_in_date as length_of_stay
from bookings;

方案2:带关联的子查询(适用于复杂场景)

如果必须用子查询,需通过主键将子查询与主表关联:

select 
  b2.price_total, 
  b2.check_in_date, 
  b2.check_out_date,
  b2.price_total / table1.length_of_stay as price_per_day, 
  table1.length_of_stay
from
(select booking_id, check_out_date - check_in_date as length_of_stay
from bookings)as table1
join bookings b2 on table1.booking_id = b2.booking_id;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 19:40:35