I have a one-to-many relationship between these two tables: menus ------ menu_id(primary key) menu_title menu_items ------------ menu_item_id menu_item_parent(foreign key) menu_item status The menu_item_status field can be set to 'published', 'unpublished' or 'deleted'. I want to retrieve the menu_title from menus, along with three fields containing the number of corresponding published, unpublished & deleted items within menu_items. How do I do this in just one statement?
since it is one to many you won't have problem retrieving them. SELECT menu_id, menu_title, menu_item_id, menu_item_parent, menu_item_status FROM menus JOIN menu_items ON menu_id = menu_item_parent and for counts query will be.. SELECT menu_id, menu_title, SUM(IF(menu_item_status = 'published', 1, 0)) as Published, SUM(IF(menu_item_status = 'unpublished', 1, 0)) as Unpublished, SUM(IF(menu_item_status = 'deleted', 1, 0)) as Deleted FROM menus JOIN menu_items ON menu_id = menu_item_parent group by menu_id hope this solves it...
Works, thanks! Just had to make it a LEFT JOIN so that all the menus would display and not just the ones that had menu items.