So I am trying to do this process and want to avoid doing multiple db calls. I want to:
- Insert values into database
- After insert, increment a column 'count' based off similar values 'ticket_number'
- And I want to use a trigger to automate it on insert
What I have so far:
CREATE OR REPLACE TRIGGER ChatAutoIncrement
ON chat
FOR INSERT
BEGIN
UPDATE chat
SET
count = ( ( SELECT u.cnt FROM ( SELECT ticket_id, count(*) as cnt FROM chat GROUP BY ticket_id ) u ) WHERE u.cnt > 1 )
WHERE
ticket_id IN
(
SELECT u.ticket_id, u.cnt
FROM
(
SELECT ticket_id, count(*) as cnt
FROM chat
GROUP BY ticket_id
) u
where u.cnt > 1
GROUP BY u.ticket_id
);
END;
This is what Workbench suggested:
CREATE DEFINER = CURRENT_USER TRIGGER `blil_insurance`.`ChatAutoIncrement` AFTER INSERT ON `chat` FOR EACH ROW
BEGIN
UPDATE chat
SET
count =
(
SELECT u.cnt
FROM
(
SELECT ticket_id, count(*) as cnt
FROM chat
GROUP BY ticket_id
) u
where u.cnt > 1
GROUP BY u.ticket_id
)
WHERE
ticket_id IN
(
SELECT u.ticket_id, u.cnt
FROM
(
SELECT ticket_id, count(*) as cnt
FROM chat
GROUP BY ticket_id
) u
where u.cnt > 1
GROUP BY u.ticket_id
);
END
The table looks like this:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…