2013-06-18 58 views
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 and a.col_name2= 
    302885 group by b.candidate_id; 

這是查詢工作正常,我無效使用組運行的同時使用GROUP BY

但是當我使用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)

提前請幫me.Thanks ..

+0

@echo_Samir感謝編輯 – PSR

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

當USI NG組通過你需要指定組的WHERE子句HAVING子句中:

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

修正/改進:

  • 格式化
  • 按列
+0

如果我給它302885工作正常 – PSR

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