I got a table with products and a table with reviews of the products. The products-table has the parent- and child-products. The parent-products should get all reviews from the child-products. I did:
DROP TABLE IF EXISTS products;
CREATE TABLE products (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`parent` int(10) unsigned DEFAULT NULL,
`review` decimal(3,2) DEFAULT NULL,
PRIMARY KEY(id)
);
DROP TABLE IF EXISTS reviews;
CREATE TABLE reviews (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`product` int(10) unsigned NOT NULL,
`review` decimal(3,2) DEFAULT NULL,
PRIMARY KEY(id)
);
INSERT INTO products SET id=1, parent=null;
INSERT INTO products SET id=2, parent=1;
INSERT INTO products SET id=3, parent=1;
INSERT INTO reviews SET product=2, review=5;
INSERT INTO reviews SET product=3, review=5;
INSERT INTO reviews SET product=3, review=4;
INSERT INTO products SET id=4, parent=null;
INSERT INTO products SET id=5, parent=4;
INSERT INTO reviews SET product=5, review=4;
INSERT INTO reviews SET product=5, review=2;
UPDATE products
SET products.review=
(SELECT SUM(reviews.review)/COUNT(reviews.review) FROM reviews
LEFT JOIN products p ON p.parent = products.id
)
WHERE products.parent IS NULL;
But with that I'm surprised I'm getting an error:
ERROR 1054 (42S22): Unknown column 'products.id' in 'on clause'
Any suggestions on how to do it correctly? The idea is that product 1 should get a review of 14/3 = 4.66 and product 4 should get a review of 6/2 = 3.