mysql select with joins and pivot table -
i have 4 tables: brands, category, brands_category, , files. brands , category linked brands_category has 2 columns: brand_id , category_id
## brands ## id | name | url | .. ## category ## id | name | order | .. ## brands_category ## brand_id | category_id ## files ## id | name | path | brand_id | uploaded_at i want distinct brands of category , order uploaded_at files table without duplication of brands. have made quite few attempts cant results want. here success i've had:
select b.*, aa.uploaded_at brands b inner join (select bc.brand_id, f.uploaded_at brands_category bc inner join brands b on b.id = bc.brand_id inner join category c on c.id = bc.category_id inner join files f on f.brand_id = bc.brand_id c.id = 1 group bc.brand_id order bc.brand_id desc, f.uploaded_at desc) aa on b.id = aa.brand_id i brands category of 1 latest uploaded_at date isn't being return when brand has multiple files associated it.
no need pivot table -- use standard joins:
select b.brand_id brands b join brands_category bc on b.brand_id = bc.brand_id join category c on bc.category_id = c.category_id join files f on b.brand_id = f.brand_id c.category_name = 'some category' order f.uploaded_at
Comments
Post a Comment