简体   繁体   中英

MySQL trigger before insert check if email exists

I have designed a C# windows Form with textboxes that inserts a new employee or new customer with an inserted by textbox email, that checks by sql if that email exist to create a new user (if requires)

this 3 tables are in mysql code

CREATE TABLE users (
    idUser int AUTO_INCREMENT,
    emailUser varchar(50) not null unique,
    nameUser varchar(50) not null,
    userSince datetime,
    PRIMARY KEY (idUser)
);

CREATE TABLE customers (
    idCustomer int auto_increment,
    idUser int,
    typeCustomer int,
    PRIMARY KEY (idCustomer),
    FOREIGN KEY (idUser) REFERENCES users(idUser),
    FOREIGN KEY (typeCustomer) REFERENCES typeCustomer(idTypeCustomer)
);

CREATE TABLE employees (
    idEmployee int auto_increment,
    idUser int,
    typeEmployee int,
    PRIMARY KEY (idEmployee),
    FOREIGN KEY (idUser) REFERENCES users(idUser),
    FOREIGN KEY (typeEmployee) REFERENCES typeEmployee(idTypeEmployee)
);

So I would like to know if a SQL trigger could check all rows in users table, and how. I still dont understand triggers and procedures >.<

Trigger will run after record inserted to users

CREATE TRIGGER after_users_insert
    AFTER INSERT
    ON users FOR EACH ROW
    BEGIN
        INSERT INTO customers (idUser , typeCustomer)
        VALUES(new.id, 1);
        INSERT INTO customers (employees , typeEmployee)
        VALUES(new.id, 1);
    END$$



Insert into users (emailUser, nameUser) 
SELECT 'test@email.com', 'test' WHERE NOT EXISTS (SELECT 1 FROM users  WHERE emailUser = 'test@email.com' )

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