简体   繁体   中英

MySQL: Update with join in subquery

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.

The products is not visible in the subquery. Use following syntax instead:

UPDATE products pp
LEFT JOIN (
  SELECT pc.parent, SUM(r.review)/COUNT(r.review) as 'rev'
  FROM reviews r
    LEFT JOIN products pc on r.product = pc.id
  GROUP BY pc.parent
) pcc ON pcc.parent = pp.id  
SET pp.review=pcc.rev
WHERE pp.parent IS NULL;

Since you've declared p as an alias for the products table, you need to use it throughout the query. So, in your LEFT JOIN clause just use p.parent instead of products.parent .

UPDATE products
SET products.review=
(SELECT SUM(reviews.review)/COUNT(reviews.review) FROM reviews 
LEFT JOIN products p ON p.parent = p.id
)
WHERE products.parent IS NULL;

At its heart, you appear to be looking for this value:

SELECT SUM(r.review)/(SELECT COUNT(*) FROM products) n FROM reviews r;
+----------+
| n        |
+----------+
| 4.666667 |
+----------+

So, something like...

UPDATE products x 
  JOIN (SELECT SUM(r.review)/(SELECT COUNT(*) FROM products) n FROM reviews r) y
   SET x.review = y.n
 WHERE x.review IS NULL;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM