Mysql unique constraint allowing single row for a combination

前端 未结 5 1237
囚心锁ツ
囚心锁ツ 2021-01-20 01:25

Is it possible to have a unique constraint such that one particular column has a value only once?

For instance

-----------------------    
name | pri         


        
5条回答
  •  广开言路
    2021-01-20 01:53

    A normal way to do this is to extract a separate table to hold the default price :

    CREATE TABLE price (
        name VARCHAR(255),
        price INT,
        PRIMARY KEY (name, price)
    ) ;
    
    CREATE TABLE defaultPrice (
        name VARCHAR(255),
        price INT,
        PRIMARY KEY (name),
        FOREIGN KEY(name, price) REFERENCES price(name, price)
    );
    

    Most people will advise introducing surrogate keys:

    CREATE TABLE item (
        id INT PRIMARY KEY,
        name VARCHAR(255),
        UNIQUE(name)
    );
    
    CREATE TABLE price (
        itemId INT,
        price INT,
        PRIMARY KEY (itemId, price),
        FOREIGN KEY (itemId) REFERENCES item (id)
    ) ;
    
    CREATE TABLE defaultPrice (
        itemId INT,
        price INT,
        PRIMARY KEY (itemId),
        FOREIGN KEY (itemId, price) REFERENCES price (itemId, price)
    );
    

提交回复
热议问题