MySQL:使用子查询中的join更新

时间:2018-08-15 10:35:28

标签: mysql

我有一张摆有产品的桌子和一张摆有产品评论的桌子。产品表包含父产品和子产品。父产品应获得子产品的所有评论。我做到了:

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;

但是,令我惊讶的是我遇到了一个错误:

  

错误1054(42S22):“ on子句”中的未知列“ products.id”

有关如何正确执行操作的任何建议?这个想法是,产品1的评论应为14/3 = 4.66,产品4的评论应为6/2 = 3。

3 个答案:

答案 0 :(得分:3)

该产品在子查询中不可见。请改用以下语法:

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;

答案 1 :(得分:0)

由于已将p声明为products表的别名,因此需要在整个查询中使用它。因此,在您的LEFT JOIN子句中,只需使用p.parent而不是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;

答案 2 :(得分:0)

从本质上讲,您似乎正在寻找该值:

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

所以,类似...

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;