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

SQL嵌套查询构建求助:关联两表获取空座位及airline_id

解决方案

方法1:使用JOIN关联表

先统计每架飞机的总预订座位数,再关联airlines_detail表获取航空公司ID并计算空座位:

SELECT 
    ad.airline_id,
    ad.airplane_id,
    ad.total_seats,
    COALESCE(b.booked_total, 0) AS booked_total,
    ad.total_seats - COALESCE(b.booked_total, 0) AS empty_seats
FROM 
    airlines_detail ad
LEFT JOIN 
    (
        SELECT 
            airplane_id,
            SUM(booked) AS booked_total
        FROM 
            Bookings
        GROUP BY 
            airplane_id
    ) b ON ad.airplane_id = b.airplane_id;
  • 使用LEFT JOIN可保证无预订记录的飞机也能出现在结果中
  • COALESCE用来处理无预订时的NULL值,将预订总和默认为0

方法2:使用子查询

直接在主查询中嵌入子查询获取对应飞机的预订总和:

SELECT 
    airline_id,
    airplane_id,
    total_seats,
    (SELECT SUM(booked) FROM Bookings b WHERE b.airplane_id = ad.airplane_id) AS booked_total,
    total_seats - COALESCE((SELECT SUM(booked) FROM Bookings b WHERE b.airplane_id = ad.airplane_id), 0) AS empty_seats
FROM 
    airlines_detail ad;
  • 写法更简洁,但数据量较大时,JOIN方式的性能表现通常更优

注意事项

  • 确保airlines_detail表的total_seats为数值类型,避免计算时出现类型错误
  • 若Bookings表存在airplane_id为空的记录,需在分组或子查询中添加WHERE airplane_id IS NOT NULL过滤无效数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 16:09:26