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

时间:2019-02-28 14:20:09

标签: mysql sql select union-all

我在查询中遇到此错误,您是否知道如何将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列。

2 个答案:

答案 0 :(得分:1)

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

where at.startDate between @startDate and @endDate 

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

答案 1 :(得分:1)

我没有在主select子句中包含selects,而是创建了一个要联接的子查询,以便可以检查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

希望重组查询时我什么都没有搞乱:)