mysql group by and filtering the values in each grouped record -
i have table of users im grouping age, each user has nationality , if 1 of users nationality want value in group record, seems take first nationality finds, how can write query?
one way be:
select *, if(instr(group_concat('--', nationality, '--'), '--us--'), 'us', nationality) table group age;
what group_concat combines nationalities of 1 age , if finds string 'us' among them, returns 'us' , otherwise returns nationality do. adds '--' in beginning , end of nationality make 'us' become '--us--'. if didn't that, query think other nationality contains consecutive characters 'us' mean us. '--' characters used internally , not shown in final result.
edit: (cleaner longer) way came mind:
select * (select * table nation='us' union select * table nation!='us') tmp group age;
so, first select persons nationality us, select persons nationality not , combine 2 sets of persons table of persons in order there first persons , others. perform group operation table , you'll nationality if there's @ least 1 person in age, because come first.
Comments
Post a Comment