SELECT
b.idd as model_nr,
b.tytul_model,
coalesce(m.size,0) as size,
min(m.cena_detal_old) as cena_old, m.dataold as data_old,
ap.lm as pod_asort,ap.opis as pod_asort_lp,
a.zloto,
m.proba as proba,m.wyrob
,b.asort as asortyment,
a.lppl as Nazw,a.lmpl as lm ,a.sym,b.numer,b.wersja,w.wersja as wer,
sum(m.szt) as sztuki,
round(sum(m.waga)/count(*),2) as swaga,
g.opis as opis_grupy,
m.jed,m.cena_jedn,
if(coalesce(m.cena_detal,0)=0,m.cena_jedn*((100+190)/100),m.cena_detal) as cena_jedn_detal,
czas,b.foto_jest,m.pmagi,m.ile_jest,coalesce(m.sale,0) as sale,min(coalesce(m.cena_sale,0)) as cena_sale,coalesce(g.sale_procent,0) as sale_procent
,coalesce(b.wyprzedaz,0) as wyprzedaz,
m.cena_sale, coalesce(b.foto_hover,0) as foto_hover
FROM
(
select m.wyrob,m.data_d,m.size,
min(m.waga) as waga,
count(*) as szt,m.kod,m.proba,m.jed,
min(m.cena_jedn) as cena_jedn,
min(m.cena_detal) as cena_detal,
min(m.cena_detal_old) as cena_detal_old,
m.jest,m.numer,m.asortyment,m.wersja,m.grupa_cen,
min(coalesce(pm.czas_dostawy,0)) as czas ,max(m.data_d) as datad,
max(m.data_old) as dataold,
sum(if(m.jest=0,1,NULL)) as ile_jest,coalesce(m.sale,0) as sale,
min(coalesce(m.cena_sale,0)) as cena_sale
##,group_concat(DISTINCT pm.nazwa order by pm.id SEPARATOR '#') as pmagi
,'X' as pmagi
from
(
select asort,numer,wersja
from baza_tagi bt
where ( bt.tag_id='50' or bt.tag_id='85' ) and ( bt.asort='1' or bt.asort='18' )
group by asort,numer,wersja
having count(tag_id)=2
) z , magazyn m USE INDEX(`w_j_n_l_r_a_pm`)
left join pmagazyny pm on m.pmag=pm.id
LEFT JOIN baza_producent bp ON m.Asortyment=bp.asort AND m.numer=bp.numer AND m.wersja=bp.wersja and bp.producent>0
where m.jest=0 and m.numer>=0 and coalesce(m.logo,0)=0 and coalesce(m.rodzaj,0)=0 and ( m.asortyment='1' or m.asortyment='18' ) and ( pm.activ=1 or pm.activ=3 or ( pm.activ=2 and bp.producent=1244 ) ) and m.asortyment=z.asort and m.numer=z.numer and m.wersja=z.wersja
group by m.asortyment,m.numer,m.wersja,m.proba,m.size
) as m
inner join baza b on (b.asort=m.asortyment and b.numer=m.numer and b.wersja=m.wersja and coalesce(b.foto_jest,0)>0)
left join asortyment a on a.Id=b.asort
left join asort_pod ap on ap.id=b.asort_pod
left join wersje w on b.wersja=w.id_wersja
#left join grupy g on if(m.sale>0,m.sale=g.nr, m.grupa_cen=g.nr)
left join grupy g on g.nr=m.grupa_cen
where ( m.asortyment<200 and ( m.asortyment='1' or m.asortyment='18' ) and ( round(m.size)='11' or round(m.size)='15' or round(m.size)='17' or round(m.size)='20' or round(m.size)='23' or round(m.size)='26' ) ) and m.jest=0 group by m.asortyment,m.numer,m.wersja,m.proba
having 1=1