sql - MySQL: Average and join two queries -
i have 2 queries:
select s.id id, g.id group_id, g.nazwa group_name, s.nazwa station_name, s.szerokosc szerokosc, s.dlugosc dlugosc, s.95 p95, s.98 p98, s.diesel diesel, s.dieseltir dieseltir, s.super98 s98, s.superdiesel sdiesel, s.lpg lpg, s.ulica ulica, s.kodpocztowy kod_pocztowy, s.miasto miasto, w.id wojewodztwo_id, w.nazwa wojewodzto_nazwa, k.id kraj_id, k.kod kraj_kod, k.nazwa kraj_nazwa, s.data date_mod, s.active active stacje_main s join stacje_grups g on (s.grupa=g.id) join wojewodztwa w on (s.wojewodztwo=w.id) join kraje k on (w.kraj=k.id) s.data > 0; and
select avg(rr.vote) average, count(rr.station_id) counter stacje_ratings rr group rr.station_id; in second query not id (station_id) present, , doubled. join station_id id, , give average value of rate each id.
the problem when no rate, value in question in average , counter have 0.
when combined these queries see id, has present station_id. want see all.
you need use left join (see mysql join syntax).
this return null rows have no matching row in joined table, use coalesce replace them 0.
select s.id id, g.id group_id, -- [...] coalesce( x.average, 0 ) average coalesce( x.counter, 0 ) counter stacje_main s join stacje_grups g on (s.grupa=g.id) join wojewodztwa w on (s.wojewodztwo=w.id) join kraje k on (w.kraj=k.id) left join ( select rr.station_id avg(rr.vote) avarge, count(rr.station_id) counter stacje_ratings rr group rr.station_id ) x on ( x.station_id = s.id ) s.data > 0;
Comments
Post a Comment