繁体   English   中英

MySQL 在插入前触发检查 email 是否存在

[英]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)

这 3 个表在 mysql 代码中

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)
);

所以我想知道 SQL 触发器是否可以检查用户表中的所有行,以及如何检查。 我还是不明白触发器和程序>.<

触发器将在记录插入用户后运行

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' )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM