Enforce unique values across two tables

后端 未结 7 1252
慢半拍i
慢半拍i 2021-01-01 20:48

Is it possible to enforce uniqueness across two tables in MySQL?

I have two tables, both describing users. The users in these tables were for two different systems p

7条回答
  •  一整个雨季
    2021-01-01 21:00

    You can't declare a UNIQUE constraint across multiple tables, and MySQL does not support CHECK constraints at all. But you can design a trigger to search for the matching value in the other table. Here's a test SQL script:

    DROP TABLE IF EXISTS foo;
    CREATE TABLE FOO (username VARCHAR(10) NOT NULL);
    
    DROP TABLE IF EXISTS bar;
    CREATE TABLE BAR (username VARCHAR(10) NOT NULL);
    
    DROP TRIGGER IF EXISTS unique_foo;
    DROP TRIGGER IF EXISTS unique_bar;
    
    DELIMITER //
    
    CREATE TRIGGER unique_foo BEFORE INSERT ON foo
    FOR EACH ROW BEGIN
      DECLARE c INT;
      SELECT COUNT(*) INTO c FROM bar WHERE username = NEW.username;
      IF (c > 0) THEN
        -- abort insert, because foo.username should be NOT NULL
        SET NEW.username = NULL;
      END IF;
    END//
    
    CREATE TRIGGER unique_bar BEFORE INSERT ON bar
    FOR EACH ROW BEGIN
      DECLARE c INT;
      SELECT COUNT(*) INTO c FROM foo WHERE username = NEW.username;
      IF (c > 0) THEN
        -- abort insert, because bar.username should be NOT NULL
        SET NEW.username = NULL;
      END IF;
    END//
    
    DELIMITER ;
    
    INSERT INTO foo VALUES ('bill');  -- OK
    
    INSERT INTO bar VALUES ('bill');  -- Column 'username' cannot be null
    

    You also need similar triggers ON UPDATE for each table, but you shouldn't need any triggers ON DELETE.

提交回复
热议问题