Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update table with counts from another

Tags:

sql

mysql

Im trying to update a table with the counts of another table. I think I've got the structure of the query right but I keep getting a SQL error:

UPDATE c
SET c.sales = p.ProductCount
FROM products c
INNER JOIN
(SELECT p_key, COUNT(*) AS ProductCount 
FROM sales
GROUP BY p_key) p
ON c.link = p.p_key

The structure of the two tables:

Products product_name (varchar), sales (int), link (char),

Sales email (char), p_key (char)

I've just shown the key columns. Any help appreciated.

like image 346
Abs Avatar asked Nov 30 '22 02:11

Abs


2 Answers

You are using the join syntax for T_SQL, in MySQL do this,

UPDATE  products c
        INNER JOIN 
        (
            SELECT  p_key,
                    COUNT(*) AS ProductCount
            FROM sales
            GROUP BY p_key
        ) p
            ON c.link = p.p_key
SET c.sales = p.ProductCount
like image 185
John Woo Avatar answered Dec 10 '22 03:12

John Woo


Here is the right syntax:

UPDATE products c
INNER JOIN
(
   SELECT p_key, COUNT(*) AS ProductCount 
   FROM sales
   GROUP BY p_key
) p ON c.link = p.p_key
SET c.sales = p.ProductCount
like image 40
Mahmoud Gamal Avatar answered Dec 10 '22 03:12

Mahmoud Gamal