2010-07-21 64 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 

,并留下的东西剩下,因为它们。