0

Any idea how to get test_trigger working?

Create table test (
    book_id Int UNSIGNED NOT NULL,
    book_views Int UNSIGNED NOT NULL DEFAULT 0,
Primary Key (book_id)) ENGINE = InnoDB;

Create table trigger_test (
    book_id Int UNSIGNED NOT NULL,
    book_views Int UNSIGNED NOT NULL DEFAULT 0,
Primary Key (book_id)) ENGINE = Memory;

delimiter $$
CREATE TRIGGER test_trigger
   AFTER UPDATE ON test
   FOR EACH ROW
   BEGIN
     DECLARE rows_count INT;
     SELECT count(1) FROM trigger_test WHERE book_id=NEW.book_id INTO @rows_count;

     IF @rows_count = 0 THEN
         INSERT INTO trigger_test(book_id, book_views)
         SELECT book_id, book_views FROM test where book_id = NEW.book_id;
     ELSE
         UPDATE trigger_test
         SET book_views = NEW.book_views
         WHERE book_id = NEW.book_id;
     END IF;
   END$$
delimiter ;

Insert/update is not working. Following code should insert row in trigger_test but its not inserting row.

insert into test values (1, 10);
1
  • It is not inserting/updating record. Commented Oct 9, 2011 at 21:47

2 Answers 2

1

There is no need to reference the table 'test'. Just use the NEW table like this

INSERT INTO trigger_test(book_id,book_views)
VALUES (NEW.book_id,NEW.book_views); 

Also you could use the Replace statement.

MySQL Replace Syntax

REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.

Sign up to request clarification or add additional context in comments.

1 Comment

You can test it with a simple select. SELECT 'Trigger Invoked';
0

The trigger is an 'AFTER UPDATE' trigger ... It won't be executed after an INSERT statement.

What you are looking for is more likely to use an 'AFTER INSERT' trigger on table test.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.