0

I want to perform a case update, unfortunately I am getting an error that tells me that am making an Invalid use of group function

Error Code: 1111. Invalid use of group function

update  l,   m
    set l.requests = sum(
            case when m.event = 'rRequested' then  
                m.id end  )
    where 
        l.id = m.id

or

update  l,   m
    set l.requests =  (
            case when m.event = 'rRequested' then  
                count(m.id) end  )
    where 
        l.id = m.id

Any idea how can i fix this?

I could do a full select after the set, but i want to learn how to use (even if it's possible) the case update for aggregations...

4

1 回答 1

0

You try to distinguish based on a m.event, and the result is a grouped value (count(m.id)). I think you should sum 0 or 1 based on your value.

update l 
set l.request = (select sum(if m.event = "rRequested", 0, 1) from m where m.id = l.id))

See MySQL Update query with left join and group by for the topic.

EDIT:

The question's focus seems to be avoiding the full subselect. I think since there are no real restrictions on l that the database has to go through all lines of m with event="rRequested". So I could imagine going once through m grouping by l.id:

update l 
inner join 
(
    select id, 
    count(*) as cnt 
    from m where  m.event = "rRequested" 
    group by id
) as grp_m on grp_m.id = l.id
set l.request = grp_m.cnt
;

It sounds a bit strange that table m has many entries with the same id, but since you gave no example, it is hard to guess.

于 2013-06-20T11:51:42.127 回答