简体   繁体   中英

Update table with counts from another

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.

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

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

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