简体   繁体   中英

How to update one table based on aggregate query form another table

Say I have two tables.

Table A

  • id
  • A_status
  • parent_id_B

Table B

  • id
  • B_status

So for each id in B can have many records in A.

Now my question is, I need to set B_status to 1 when all child entries in Table A with same parent_id_B has A_status =1, else set B_status = 2

Ex:

Table A:
id    A_status    parent_id_B
1     1           1
2     1           1
3     1           2
4     1           3
5     1           3

Table B:
id    B_status
1     0
2     0
3     0

Expected result:
Table B:
id    B_status
1     1
2     1
3     1

Now consider another scenario

Table A:
id    A_status    parent_id_B
1     1           1
2     1           1
3     2           2
4     2           3
5     1           3

Table B:
id    B_status
1     0
2     0
3     0

Expected result:
Table B:
id    B_status
1     1
2     2
3     2

I need this to work only on sqlite. Thanks

I believe this can be done like so:

UPDATE TableB
SET B_Status = 
(SELECT MAX(A_Status) FROM TableA WHERE TableA.Parent_ID_B = TableB.ID);

SqlFiddle with your second case here

In a more general case (without relying on direct mapping of A's status, you can also use a CASE ... WHEN in the mapping:

UPDATE TableB
SET B_Status = 
  CASE WHEN (SELECT MAX(A_Status) 
       FROM TableA 
       WHERE TableA.Parent_ID_B = TableB.ID) = 1
  THEN 1
  ELSE 2
END;

Edit (in the case where there are more than the original number of states):

I believe you'll need to determine 2 facts about each row, eg

  • Whether there is are any rows in table A with a status other than 1 for each B
  • And there must at least be one row for the same B
  • Or, whether the count of rows of A in state 1 = the count of all rows in A for the B.

Here's the first option:

UPDATE TableB
SET B_Status = 
  CASE WHEN 
    EXISTS
     (SELECT 1 
      FROM TableA 
      WHERE TableA.Parent_ID_B = TableB.ID 
      AND TableA.A_Status <> 1)
    OR NOT EXISTS(SELECT 1 
      FROM TableA 
      WHERE TableA.Parent_ID_B = TableB.ID)
  THEN 2
  ELSE 1
END;

Updated Fiddle

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