sql - MySQL - join in one query -
i have 2 tables:
leads
|lead_id|name| | 1| a| | 2| b| | 3| c|lead_phases
|phase_id|phase_lead_fk|phase_sort|phase_status| | 1| 1| 1| 1| | 2| 1| 2| 0| | 3| 2| 3| 1| | 4| 2| 1| 0| | 5| 2| 2| 0| | 6| 3| 1| 0| | 7| 3| 2| 1|
i have write 1 query show joined table grouped lead_id , highest value of column phase_sort.
the result receive:
|lead_id|name|phase_id|phase_sort|phase_status| | 1| a| 2| 2| 0| | 2| b| 3| 3| 1| | 3| c| 7| 7| 1|
my query:
select phase_id,phase_lead_fk,phase_sort,phase_status leads left join lead_phases on lead_id=phase_lead_fk group lead_id
you need in 2 steps
select phase_lead_fk, max(phase_sort) lead_phases group phase_lead_fk
this return hights sort value each lead; can use result filter joining 2 original tables
select * leads t1 join lead_phases t2 on t1.lead_id = t2.phase_lead_fk join ( select phase_lead_fk, max(phase_sort) max_phase_sort lead_phases group phase_lead_fk ) t3 on t2.phase_lead_fk = t3.phase_lead_fk , t2.phase_sort = t3.max_phase_sort
Comments
Post a Comment