简体   繁体   中英

Update table A based on count in table B

I have 2 tables (SALESMAN, SOLD), where the SALES table records what cars were sold each day. At night a job runs that must increase the SOLD count in the SALESMAN table. For example, here are two tables:

SALESMAN                                SALES
+-------------+-----------+------+      +------------+---------+
| SALESMANID  |  NAME     | SOLD |      | SALESMANID | VEHICLE |
|          1  |  Bob      |    1 |      |          1 |      GM |
|          2  |  Charlie  |    7 |      |          1 |   Chrys |
|          3  |  Dave     |    0 |      |          1 |      GM |
+-------------+-----------+------+      |          3 |   Dodge |
                                        |          3 |      GM |
                                        |          2 |  Hummer |
                                        +------------+---------+

After the UPDATE has run, Bob's sold count will increase to 4, Charlie's sold count will increase to 8, and Dave's sold count will increase to 2. I'm trying to create something like:

UPDATE SALESMAN SET SOLD=SOLD+( 
                                SELECT COUNT(*) 
                                FROM SALES 
                                WHERE SALESMAN.SALESMANID = SALES.SALESMANID
                              )

Is this the right way to solve the problem?

I found a similar question here: ( Updating one SQL table based on data in another table ) but it's not clear if it will selectively updates table A in their example, or all records in table A.


UPDATE: I fixed the typo above but it still doesn't work. 0 rows affected when I run the query.

UPDATE SALESMAN a, 
       (SELECT SALESMANID, COUNT(*) SALE_COUNT 
        FROM SALES 
        group by SALESMANID) b 
set a.SOLD=a.SOLD+ b.SALE_COUNT 
WHERE a.SALESMANID = b.SALESMANID;

see SQL Fiddle

yes its right your query just change this

 WHERE SALESAN.SALESMANID 

to

 WHERE SALESMAN.SALESMANID 

your demo

  • i dont know why you didnt try it your self before asking a question.
INSERT INTO SALESMAN (SALESMANID, SOLD) (SELECT SALEMANID, COUNT(*) as c FROM SOLD GROUP BY SALEMANID) ON DUPLICATE KEY UPDATE SOLD = c

您可能需要命名选择并使用.c

If the sales table is deleted after this nightly process runs, then this should work

Update m Set
   Sold = sold + 
     (Select Count(*) From Sales
      Where SalesmanId = m.SalesmanId) 
From Salesman m

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