sql - Product database - MySQL query with multiple JOINs -


first, table structure:

products table:   `id` int(11) not null auto_increment,  `title` varchar(255) collate utf8_unicode_ci not null,  `price` decimal(10,2) not null,  `list_price` decimal(10,2) not null,  `brand` int(11) not null,  `category` int(11) not null,  `image` varchar(255) collate utf8_unicode_ci not null,  `description` text collate utf8_unicode_ci not null,  `featured` tinyint(4) not null default '0',  `deleted` tinyint(4) not null default '0',  primary key (`id`)  categories table:   `id` int(11) not null auto_increment,  `category` varchar(255) collate utf8_unicode_ci not null,  `parent` int(11) not null default '0',  primary key (`id`)  brand table:   `id` int(11) not null auto_increment,  `brand` varchar(255) collate utf8_unicode_ci not null,  primary key (`id`)  stock table:   `id` int(11) not null auto_increment,  `product_id` int(11) not null,  `size` varchar(4) collate utf8_unicode_ci not null,  `stock` int(11) not null,  `sold` int(11) not null,  `reserved` int(11) not null,  primary key (`id`),  unique key `product_sizes` (`product_id`,`size`),  key `product_id` (`product_id`),  constraint `stock_ibfk_1` foreign key (`product_id`) references `products` (`id`) 

i wanted single sql query grabs products whatever criteria, , adds total stock , total sold stock table, brand name brand table, child , parent categories category table.

this attempt, doesn't work:

"select     a.title,     coalesce(sum(e.stock),0),     coalesce(sum(e.sold),0),     a.price,     c.category 'parent',     d.category 'child',     b.brand,     a.featured     products         join brand b             on a.brand = b.id         join categories c             on a.category = c.id         left join categories d             on c.parent = d.id         join stock e             on a.id = e.product_id  a.deleted = 0 order a.title asc" 

initially had series of queries instead - first getting products, grabbing categories, brands, stock/sold. i'm wondering if can in 1 query?

i quite new @ sql.

thanks @shadow, query needed, works great:

    select     a.id,     a.title,     coalesce(sum(e.stock),0) 'stock',     coalesce(sum(e.sold),0) 'sold',     a.price,     c.category 'child_category',     d.category 'parent_category',     b.brand,     a.featured     products         join brand b             on a.brand = b.id         join categories c             on a.category = c.id         left join categories d             on c.parent = d.id         join stock e             on a.id = e.product_id  a.deleted = 0 group a.id, a.title, a.price, c.category, d.category, b.brand, a.featured order a.title asc 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -