简体   繁体   中英

Mysql update count of records

I have a table 'product_records' as follows:

 id - int (6), product_group - int (7), product_subgroup - int (7), type - int(3), count_of_reports - int (6) 

At the moment the values in column count_of_reports for all records are 0.

What is the most efficient way of adding count_of_reports for every row for matching product_group, product_subgroup and type?

Example:

1, 23, 1, 1, count here (i.e. 2); 
2, 23, 2, 1, count here (i.e. 1);
3, 23, 1, 1, count here (i.e. 2); 
4, 24, 1, 3, count here (i.e. 1);

Thank you in advance.

You can use below update statement -

UPDATE product_records PR
JOIN (SELECT CONCAT(product_group, product_subgroup) ID, COUNT(DISTINCT CONCAT(product_group, product_subgroup)) NUM
      FROM product_records
      GROUP  BY CONCAT(product_group, product_subgroup)) PR2
ON CONCAT(PR.product_group, PR.product_subgroup) = PR2.ID
SET PR.count_of_reports = PR2.NUM

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