使用group by时在mysql中使用组操作无效

时间:2013-06-18 09:54:34

标签: mysql

 select a.col_name1,max(b.col_name2) from table_a , table_b b where
 a.candidate_id = 900 and a.col_name1 = b.col_name1 and a.col_name2=
  302885 group by b.candidate_id;

这是查询对我来说很好

但是当我使用max(b.col_name2)时,它会发出此错误1111 invalid use of group function

select a.col_name1,max(b.col_name2) from table_a , table_b b where
a.candidate_id = 900 and a.col_name1 = b.col_name1 and a.col_name2=
max(b.col_name2)group by b.candidate_id;

我如何使用max(b.col_name2)

请帮帮我。谢谢。

4 个答案:

答案 0 :(得分:0)

试试这个

   select a.col_name1,max(b.col_name2) 
   from table_a , table_b b 
   where a.candidate_id = 900 
   and a.col_name1 = b.col_name1 
   group by b.candidate_id 
   having a.col_name2= max(b.col_name2)

   select a.col_name1,max(b.col_name2) 
   from table_a , table_b b 
   where a.candidate_id = 900 
   and a.col_name1 = b.col_name1 
   and  a.col_name2 in ( select max(col_name2) from table_b)
   group by b.candidate_id 

答案 1 :(得分:0)

使用Group By时,您需要在Having子句中指定group的where子句:

select a.col_name1,
  max(b.col_name2) 
from table_a , table_b b 
where a.candidate_id = 900 and 
  a.col_name1 = b.col_name1 
group by b.candidate_id
having a.col_name2 = max(b.col_name2)

答案 2 :(得分:0)

仅仅因为你的查询运行并不意味着它“运作良好。”。

Mysql有一些奇怪的分组功能。

试试这个:

select
  a.col_name1,
  max(b.col_name2)
from table_a
join table_b b
  on a.col_name1 = b.col_name1
where a.candidate_id = 900
and a.col_name1 = b.col_name1
and a.col_name2 = 302885
group by a.col_name1;

更正的/改进的:

  • 格式化
  • 加入语法
  • 按列分组

答案 3 :(得分:0)

此外,始终使用显式JOIN语法...

SELECT a.col_name1
     , MAX(b.col_name2) 
  FROM table_a a
  JOIN table_b b 
    ON b.col_name1 = a.col_name1 
 WHERE a.candidate_id = 900 
 GROUP 
    BY b.candidate_id
HAVING a.col_name2 = MAX(b.col_name2);