无法深入访问字段多个子查询

时间:2015-04-17 12:40:07

标签: mysql sql subquery

我在尝试访问子查询的子查询中的选定字段时收到错误。它说“where子句中的未知列”。我还有其他子查询使用相同的字段,它们完美地工作。当我尝试在子查询中访问子查询中的字段时,似乎只会出现此问题。

我的查询的简化版

SELECT r.id, 
 (SELECT min(begindatum) 
  FROM ((SELECT begindatum FROM reservatiekamer 
         WHERE reservatieId = r.id) UNION 
        (SELECT begindatum FROM reservatiefaciliteit 
         WHERE reservatieId = r.id)) as bg)
as begindatum
FROM reservatie r

错误

#1054 - Unknown column 'r.id' in 'where clause'

背景故事,我试图选择预订的开始日期,该预订存在多个房间和设施预订(2个不同的表格)。

1 个答案:

答案 0 :(得分:1)

如果子查询始终只返回一个值,则可以使用least()

SELECT r.id, 
       least((SELECT begindatum FROM reservatiekamer WHERE reservatieId = r.id),
             (SELECT begindatum FROM reservatiefaciliteit WHERE reservatieId = r.id)
            ) as begindatum
FROM reservatie r;

实际上,这种变化会更好:

SELECT r.id, 
       least(COALESCE((SELECT MIN(begindatum) FROM reservatiekamer WHERE reservatieId = r.id), 0),
             COALESCE((SELECT MIN(begindatum) FROM reservatiefaciliteit WHERE reservatieId = r.id), 0)
            ) as begindatum
FROM reservatie r;

这假设值始终为正,这就是0存在的原因。另一个值可能更合适。

最后,您可以将逻辑移至from子句:

SELECT r.id,
       LEAST(COALESCE(rk.minbd, rf.minbd), COALESCE(rf.minbd, rk.minbd)) as begindatum
FROM reservatie r LEFT JOIN
     (SELECT reservatieId, MIN(begindatum) as minbd
      FROM reservatiekamer
      GROUP BY reservatieId
     ) rk
     ON r.id = rk.reservatieId LEFT JOIN
     (SELECT reservatieId, MIN(begindatum) as minbd
      FROM reservatiefaciliteit
      GROUP BY reservatieId
     ) rf
     ON r.id = rf.reservatieId;

coalesce()least(),如果另一个值为NULL,则会返回一个值。