2010-07-21 97 views
1

我想在MySQL中使用max()的子查詢,並且我不斷遇到錯誤。查詢的要點在下面(儘管我已經改變了字段名稱)。MySQL中的子查詢錯誤與max()

select table1.field1, table1.field2, table2.field3, table2.field4, table3.field5, 
     (select max(age) 
      from age_table 
     where age_table.person = table2.person) 
    from table1 
inner join table2 on table2.person = table1.person 
inner join table3 on table3.person = table1.person 
inner join age_table on age_table.person = table1.person 

當我嘗試,我得到一個指向

語法錯誤 '從age_table其中age_table.person = table2.person'

...但我可以弄清楚問題在哪裏。

+0

謝謝,OMG小馬...我想知道爲什麼它都顯示在同一行! – chimeracoder 2010-07-21 22:04:59

回答

3

使用表別名表之間區分,而不必使用完整的表名:

SELECT t1.field1, t1.field2, t2.field3, t2.field4, t3.field5, 
     (SELECT MAX(at.age) 
      FROM AGE_TABLE at 
     WHERE at.person = t2.person) AS max_age 
    FROM TABLE1 t1 
    JOIN TABLE2 t2 ON t2.person = t1.person 
    JOIN TABLE3 t3 ON t3.person = t1.person 

我刪除似乎是多餘的JOIN到AGE_TABLE,看到它沒有在使用SELECT子句。

爲派生列值定義列別名也很好 - 習慣使它們更易於引用。有關示例,請參閱「max_age」。

1

您需要爲您的子查詢如創建別名:

(select max(age) from age_table where age_table.person = table2.person) temp 

,並留下的東西剩下,因爲它們。