MySQL不存在未知列错误

时间:2017-05-04 12:34:14

标签: php mysql sql

几个小时我一直在研究这个问题。

我在MySQL中有一个名为person_state的表

----------
person_state
----------------------------
id | person_id | state | date
----------------------------

我需要活跃的人员上次激活日期,每个人的状态已被多次更改(状态为:主动,被动,等待,阻止)。如果一个人被激活然后被停用,我的查询就不应该得到它。

我的查询是

select id as activation_id, person_id as active_person_id
  from person_state
  where state = 'active' 
  and
  not exists(
         select * from person_state 
         where person_id = active_person_id
         and
         id > activation_id
    ) 

我在'where子句' 中收到错误 未知列'active_person_id'。

感谢您的时间

3 个答案:

答案 0 :(得分:1)

WHERESELECT之前执行,因此,您不能在其中使用列别名,请尝试使用列名,例如:

select id as activation_id, person_id as active_person_id
  from person_state ps
  where state = 'active' 
  and
  not exists(
         select id from person_state 
         where person_id = ps.person_id
         and
         id > ps.activation_id
    )

答案 1 :(得分:1)


您可以使用以下查询

select P.id as activation_id, P.person_id as active_person_id
  from person_state P
  where state = 'active' 
  and
  not exists(
         select 1 from person_state 
         where person_id = P.active_person_id
         and
         id > P.activation_id
    ); 

您错过了提供别名。您可以给1或*来选择日期。但是1检查存在时运行速度更快,并且只搜索一列

答案 2 :(得分:1)

如果表中有多个列,则应使用限定列名:

select ps.id as activation_id, ps.person_id as active_person_id
from person_state ps
where ps.state = 'active' and
      not exists (select *
                  from person_state ps2
                  where ps2.person_id = ps.person_id and
                        ps2.id > ps.id
                 ) ;

您的主要问题是您无法在子查询中使用列别名。