I have three tables in a database:
- Product table – +100000 entries
- Attribute table (list of possible attributes of a product)
- Product attribtue table (which contains the value of the attribute of a product)
I am looking for 8 random products and one of their attributes (attribute_id = 2), but if a product hasn’t this attribute it should appear at the return of the query. I have been trying some sql queries without any succesful result because my return only shows the products that have the attribute and hide the others.
My three tables are like this:
CREATE TABLE `product` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `sku` varchar(20) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', `name` varchar(90) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', `provider_id` int(11) unsigned DEFAULT NULL, `url` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `active` int(1) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `sku_UNIQUE` (`sku`) ) ENGINE=InnoDB AUTO_INCREMENT=123965 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; CREATE TABLE `attribute` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL DEFAULT '', `data_type` varchar(50) DEFAULT '', PRIMARY KEY (`id`), ) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=latin1; CREATE TABLE `product_attribute` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `product_id` int(11) unsigned NOT NULL, `attribute_id` int(11) unsigned NOT NULL DEFAULT '6', `value` longtext NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `product_id` (`product_id`,`attribute_id`) ) ENGINE=InnoDB AUTO_INCREMENT=869437 DEFAULT CHARSET=latin1;
And this is one of the queries I tried, I thought it was correct but it have the same problem as the others…
SELECT product.id, product.sku, product.name,provider.name as provider_name, product_attribute.value as author FROM (`product`) LEFT JOIN `provider` ON `product`.`provider_id` = `provider`.`id` LEFT JOIN `product_attribute` ON `product`.`id` = `product_attribute`.`product_id` WHERE `product`.`active` = '1' AND `product`.`url` IS NOT NULL AND (`product_attribute`.`attribute_id` = 8 OR `product_attribute`.`attribute_id` IS NULL) AND `product`.`provider_id` = '7' ORDER BY RAND() LIMIT 8
I was trying with left, inner and right join and nothing works.
Advertisement
Answer
You should put the condition for the left-joined table in the join, not the where clause
... from product left join provider ON product.provider_id = provider.id left join product_attribute on product.id = product_attribute.product_id and product_attribute.attribute_id = 8 where `product`.`active` = '1' and `product`.`url` IS NOT NULL and `product`.`provider_id` = '7' ...