简体   繁体   中英

SQL Trigger to copy value from Table A - Column A to Table B - Column A IF Value is unique in Table B

I have two tables:

Table A with multiple columns and Table B with two columns.

What I want to do after inserting a new row in to Table A is:

  1. Check to see if the value that was inserted in to Table A - Column C is already in Table B
  2. If the value is not in Table B insert the data from Table A - Column C in to Table B - Column B and set Table B - Column C to a value of 1
  3. If the value in Table A - Column C is already present in Table B , then locate the ROW and increment the value in Table B - Column C by 1

Hope someone can help as I'm unable to find a solution to this.

Thanks for any help you can provide.

The following is Oracle syntax, so someone will need to translate this into MYSQL. The work done in a trigger should always be kept to a minimum, so the other writers are correct when they say you may want to find a different way of doing this.

I found your references to columns confusing, so I am substituting FK and PK for the column names.

CREATE OR REPLACE TRIGGER tablea
   AFTER INSERT OR DELETE
   ON tablea
   REFERENCING NEW AS new OLD AS old
   FOR EACH ROW
BEGIN

   IF INSERTING
   THEN

      UPDATE tableb
         SET cnt   = cnt + 1
       WHERE fk = :new.pk;

      IF SQL%ROWCOUNT = 0
      THEN

         INSERT INTO tableb (
                        fk, cnt
                     )
              VALUES (:new.pk, 1);

      END IF;

   END IF;

   IF DELETING
   THEN

      UPDATE tableb
         SET cnt   = cnt - 1
       WHERE fk = :old.pk;

   END IF;

END;

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