Tentando usar um gatilho para a) preencher uma nova coluna top_category
com valores à esquerda de dois pontos, encontrados em category
, então b) Se não houver dois pontos, coloque todo o valor de inserção em top_category
. Não consigo estruturar esse segundo gatilho para criação.
CREATE TABLE qn_txs (
id SERIAL PRIMARY KEY,
category VARCHAR(250),
top_category VARCHAR(250)
);
-- Stage 1 trigger works
-- CREATE TRIGGER `t_add_top_category1` BEFORE INSERT ON `qn_txs`
-- FOR EACH ROW
-- SET NEW.`top_category` = LEFT(NEW.category, INSTR(NEW.category, ":") - 1);
DELIMITER //
CREATE TRIGGER `t_add_top_category2` BEFORE INSERT ON `qn_txs`
FOR EACH ROW BEGIN
SET NEW.`top_category` = LEFT(NEW.category, INSTR(NEW.category, ":") - 1)
-- make sure top_category is not null if there is a value in category
IF (NEW.`top_category` = '')
THEN
SET NEW.`top_category` = NEW.`category`;
END IF;
END//
DELIMITER;
INSERT INTO qn_txs (category)
VALUES ('I should also be a top cat'), ('bananas:green'), ('baseball:table'), (''), ('Very long string: with spaces');
SELECT * FROM qn_txs;
Aqui está uma tabela da saída desejada após a conclusão da inserção.
eu ia | categoria | categoria_principal |
---|---|---|
1 | Eu também deveria ser um gato top | Eu também deveria ser um gato top |
2 | bananas:verde | bananas |
3 | beisebol: mesa | beisebol |
4 | ||
5 | String muito longa: com espaços | Corda muito longa |