2017-05-04 84 views
0

幾個小時我一直在處理這個問題。MySQL不存在未知列錯誤

我已經在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'。

感謝您的時間

+0

使用表別名。 – jarlh

+0

我認爲你問的數據庫錯誤的SQL我認爲你需要更多的東西像'GROUP BY person_id HAVING SUM(state ='active')= 1 AND SUM(state ='passive')= 0' ...但是IAM不知道,無法測試它沒有示例數據和預期的輸出 –

回答

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 
    ) 
+0

@Ali insan - 不要在選擇中使用*。您可以使用** SELECT 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的工作速度更快,因爲它會檢查存在的,而且只針對一列搜索

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 
       ) ; 

你的主要問題是:您不能在子查詢中使用列別名。