2014-11-01 76 views
1

晚上好! 我有問題,因爲我不能在WHERE和 ORDER BY中使用MAXGROWTHPARENT值。 我寫了這條查詢:POSTGRESQL:在WHERE子句中使用之前的計算值

SELECT PERSON.*, 
(
    SELECT MAX(PARENT.GROWTH) 
    FROM MAN PARENT 
    WHERE 
     (PARENT.ID = PERSON.ID_FATHER) 
    OR 
     (PARENT.ID = PERSON.ID_MOTHER) 
) AS MAXGROWTHPARENT 
FROM MAN PERSON 
WHERE PERSON.GROWTH > 
(
    SELECT MAX(PARENT.GROWTH) 
    FROM MAN PARENT 
    WHERE 
     (PARENT.ID = PERSON.ID_FATHER) 
    OR 
     (PARENT.ID = PERSON.ID_MOTHER) 
) 
ORDER BY (PERSON.GROWTH - 
    (
     SELECT MAX(PARENT.GROWTH) 
     FROM MAN PARENT 
     WHERE 
      (PARENT.ID = PERSON.ID_FATHER) 
     OR 
      (PARENT.ID = PERSON.ID_MOTHER) 
    ) 
); 

我的代碼看起來非常難看。你能告訴我如何在WHERE和ORDER BY子句中使用MAXGROWTHPARENT ?

回答

1

我覺得兩個獨立的加入可以更好地工作:

select p.*, greatest(pf.growth, pm.growth) as MAXGROWTHPARENT 
from man p left join 
    man pf 
    on p.id_father = pf.id_father left join 
    man pm 
    on p.id_mother = pm.id_mother 
order by p.growth - greatest(pf.growth, pm.growth); 

注:如果連接可能不匹配,你可能更喜歡:

select p.*, greatest(coalesce(pf.growth, pm.growth), coalesce(pm.growth, pf.growth)) as MAXGROWTHPARENT 
from man p left join 
    man pf 
    on p.id_father = pf.id_father left join 
    man pm 
    on p.id_mother = pm.id_mother 
order by p.growth - greatest(coalesce(pf.growth, pm.growth), coalesce(pm.growth, pf.growth)); 
相關問題