简体   繁体   中英

PostgreSQL UNIQUE constraint and REFERENCES

Let's say I have a table tree and a table special_tree

CREATE TABLE tree VALUES (name VARCHAR(32) UNIQUE NOT NULL PRIMARY KEY,
                          type VARCHAR(32) NOT NULL);

CREATE TABLE special_tree VALUES (name NOT NULL REFERENCES tree(name),
                                  treat_date DATE,
                                  id INT NOT NULL PRIMARY KEY);

So I have a table containing a list of trees with unique names BUT I want to say that a tree can have multiple 'treat_date' (for various reasons). Since tree(name) is unique I can't add 2 same name in special_tree.

Is the only solution is to remove unique from tree and then add everywhere i handle the tree table an IF statement to check if name isn't already there? (IF EXISTS (SELECT name FROM tree where tree.name = ...))

If you consider the column name of the table tree it doesn't mean that all referenced columns also should have unique values. Take a look at this example

the best solution for this is (for MySQL):

CREATE TABLE tree VALUES (
  id_t int(11) NOT NULL auto_increment,
  name VARCHAR(32) NOT NULL,
  type VARCHAR(32) NOT NULL,
CONSTRAINT tree_pk PRIMARY KEY (id_t));

CREATE TABLE special_tree VALUES (
  id_st int(11) NOT NULL auto_increment,
  id_t NOT NULL REFERENCES tree(id_t),
  treat_date DATE,
  CONSTRAINT special_tree_pk PRIMARY KEY (id_st));

for PostgreSQL:

CREATE TABLE tree VALUES (
  id_t serial primary key,
  name VARCHAR(32) NOT NULL,
  type VARCHAR(32) NOT NULL);

CREATE TABLE special_tree VALUES (
  id_st serial primary key,
  id_t NOT NULL REFERENCES tree(id_t),
  treat_date DATE);

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