错误代码:1054。'where子句'中的未知列'sdate'

问题描述 投票:0回答:2

我在查询中遇到此错误,您是否知道如何将sdate放入2层子查询中?

select
at.startDate as sdate, at.dau as DAU,
(
select count(distinct d.uid) from
 (select ses.uid from dsession as ses where ses.startDate = sdate group by ses.uid
  union all
  select res.uid from rsession as res where res.startDate = sdate group by res.uid) as te
) as MAU, (SELECT DAU/MAU) as AVG
from
attendance as at 

如果我单独查询子查询,但是当我将它合并到主查询时,sdate就不知道了。任何的想法?

我试图将sdate上的where替换为at.startDate,但仍然有未知的at.startDate列。

mysql sql select union-all
2个回答
1
投票

我没有在主select子句中使用选择,而是创建了一个要加入的子查询,以便可以检查startDate

SELECT at.startDate AS sdate, at.dau AS DAU, (DAU/MAU.cnt) as AVG
FROM attendance AS at
JOIN (SELECT startdate, count(distinct uid) as cnt
      FROM (SELECT uid, startdate FROM dsession
            UNION ALL
            SELECT uid, startdate FROM rsession) as ua
      GROUP BY startdate
     ) as MAU ON MAU.startdate = at.startdate

希望在重构查询时我没有弄乱任何东西:)


1
投票

您不能在where子句中使用列别名。只需使用原始列名称:

where at.startDate between @startDate and @endDate 

别名在order by中被接受,因此不必更改。

© www.soinside.com 2019 - 2024. All rights reserved.